From ec1a1a462c144c4c8b921971ab69331e56e513df Mon Sep 17 00:00:00 2001 From: Cloud SDK Librarian Date: Wed, 21 Jan 2026 08:47:11 +0000 Subject: [PATCH] feat: generate libraries --- .librarian/state.yaml | 16 +- .../google/cloud/databasecenter/__init__.py | 8 + .../cloud/databasecenter_v1beta/__init__.py | 8 + .../databasecenter_v1beta/gapic_metadata.json | 15 + .../services/database_center/async_client.py | 83 + .../services/database_center/client.py | 81 + .../database_center/transports/base.py | 17 + .../database_center/transports/grpc.py | 29 + .../transports/grpc_asyncio.py | 35 + .../database_center/transports/rest.py | 228 + .../database_center/transports/rest_base.py | 57 + .../databasecenter_v1beta/types/__init__.py | 8 + .../types/machine_config.py | 1 - .../databasecenter_v1beta/types/service.py | 219 + ...base_center_aggregate_issue_stats_async.py | 53 + ...abase_center_aggregate_issue_stats_sync.py | 53 + ...ta_google.cloud.databasecenter.v1beta.json | 153 + .../test_database_center.py | 544 + .../docs/dialogflowcx_v3/examples.rst | 10 + .../docs/dialogflowcx_v3/playbooks.rst | 10 + .../docs/dialogflowcx_v3/services_.rst | 3 + .../docs/dialogflowcx_v3/tools.rst | 10 + .../google/cloud/dialogflowcx/__init__.py | 155 +- .../google/cloud/dialogflowcx_v3/__init__.py | 145 +- .../cloud/dialogflowcx_v3/gapic_metadata.json | 462 + .../services/agents/async_client.py | 4 + .../dialogflowcx_v3/services/agents/client.py | 26 + .../services/environments/async_client.py | 4 + .../services/environments/client.py | 22 + .../services/examples/__init__.py | 22 + .../services/examples/async_client.py | 1188 ++ .../services/examples/client.py | 1709 ++ .../services/examples/pagers.py | 197 + .../services/examples/transports/README.rst | 9 + .../services/examples/transports/__init__.py | 36 + .../services/examples/transports/base.py | 301 + .../services/examples/transports/grpc.py | 554 + .../examples/transports/grpc_asyncio.py | 626 + .../services/examples/transports/rest.py | 2002 +++ .../services/examples/transports/rest_base.py | 487 + .../services/flows/async_client.py | 10 +- .../dialogflowcx_v3/services/flows/client.py | 54 +- .../services/generators/async_client.py | 1 + .../services/generators/client.py | 1 + .../services/pages/async_client.py | 4 + .../dialogflowcx_v3/services/pages/client.py | 48 + .../services/playbooks/__init__.py | 22 + .../services/playbooks/async_client.py | 2000 +++ .../services/playbooks/client.py | 2566 +++ .../services/playbooks/pagers.py | 353 + .../services/playbooks/transports/README.rst | 9 + .../services/playbooks/transports/__init__.py | 36 + .../services/playbooks/transports/base.py | 413 + .../services/playbooks/transports/grpc.py | 766 + .../playbooks/transports/grpc_asyncio.py | 884 ++ .../services/playbooks/transports/rest.py | 3542 +++++ .../playbooks/transports/rest_base.py | 856 + .../services/sessions/async_client.py | 4 + .../services/sessions/client.py | 48 + .../services/test_cases/async_client.py | 4 + .../services/test_cases/client.py | 48 + .../services/tools/__init__.py | 22 + .../services/tools/async_client.py | 1765 +++ .../dialogflowcx_v3/services/tools/client.py | 2273 +++ .../dialogflowcx_v3/services/tools/pagers.py | 353 + .../services/tools/transports/README.rst | 9 + .../services/tools/transports/__init__.py | 36 + .../services/tools/transports/base.py | 368 + .../services/tools/transports/grpc.py | 684 + .../services/tools/transports/grpc_asyncio.py | 789 + .../services/tools/transports/rest.py | 2963 ++++ .../services/tools/transports/rest_base.py | 742 + .../transition_route_groups/async_client.py | 2 + .../transition_route_groups/client.py | 24 + .../services/webhooks/async_client.py | 2 + .../services/webhooks/client.py | 22 + .../cloud/dialogflowcx_v3/types/__init__.py | 136 +- .../cloud/dialogflowcx_v3/types/agent.py | 30 +- .../dialogflowcx_v3/types/audio_config.py | 12 +- .../cloud/dialogflowcx_v3/types/code_block.py | 44 + .../types/data_store_connection.py | 8 + .../dialogflowcx_v3/types/environment.py | 7 +- .../cloud/dialogflowcx_v3/types/example.py | 291 + .../cloud/dialogflowcx_v3/types/flow.py | 27 +- .../types/generative_settings.py | 28 + .../cloud/dialogflowcx_v3/types/generator.py | 9 + .../cloud/dialogflowcx_v3/types/page.py | 10 + .../types/parameter_definition.py | 203 + .../cloud/dialogflowcx_v3/types/playbook.py | 956 ++ .../dialogflowcx_v3/types/response_message.py | 13 + .../dialogflowcx_v3/types/safety_settings.py | 149 + .../types/security_settings.py | 5 +- .../cloud/dialogflowcx_v3/types/session.py | 132 +- .../cloud/dialogflowcx_v3/types/tool.py | 956 ++ .../cloud/dialogflowcx_v3/types/tool_call.py | 127 + .../cloud/dialogflowcx_v3/types/trace.py | 383 + .../cloud/dialogflowcx_v3/types/webhook.py | 81 + ..._v3_generated_agents_create_agent_async.py | 1 + ...w_v3_generated_agents_create_agent_sync.py | 1 + ..._v3_generated_agents_update_agent_async.py | 1 + ...w_v3_generated_agents_update_agent_sync.py | 1 + ...generated_examples_create_example_async.py | 59 + ..._generated_examples_create_example_sync.py | 59 + ...generated_examples_delete_example_async.py | 50 + ..._generated_examples_delete_example_sync.py | 50 + ...v3_generated_examples_get_example_async.py | 53 + ..._v3_generated_examples_get_example_sync.py | 53 + ..._generated_examples_list_examples_async.py | 54 + ...3_generated_examples_list_examples_sync.py | 54 + ...generated_examples_update_example_async.py | 58 + ..._generated_examples_update_example_sync.py | 58 + ...nerated_playbooks_create_playbook_async.py | 58 + ...enerated_playbooks_create_playbook_sync.py | 58 + ...playbooks_create_playbook_version_async.py | 53 + ..._playbooks_create_playbook_version_sync.py | 53 + ...nerated_playbooks_delete_playbook_async.py | 50 + ...enerated_playbooks_delete_playbook_sync.py | 50 + ...playbooks_delete_playbook_version_async.py | 50 + ..._playbooks_delete_playbook_version_sync.py | 50 + ...nerated_playbooks_export_playbook_async.py | 57 + ...enerated_playbooks_export_playbook_sync.py | 57 + ..._generated_playbooks_get_playbook_async.py | 53 + ...3_generated_playbooks_get_playbook_sync.py | 53 + ...ed_playbooks_get_playbook_version_async.py | 53 + ...ted_playbooks_get_playbook_version_sync.py | 53 + ...nerated_playbooks_import_playbook_async.py | 58 + ...enerated_playbooks_import_playbook_sync.py | 58 + ..._playbooks_list_playbook_versions_async.py | 54 + ...d_playbooks_list_playbook_versions_sync.py | 54 + ...enerated_playbooks_list_playbooks_async.py | 54 + ...generated_playbooks_list_playbooks_sync.py | 54 + ...laybooks_restore_playbook_version_async.py | 53 + ...playbooks_restore_playbook_version_sync.py | 53 + ...nerated_playbooks_update_playbook_async.py | 57 + ...enerated_playbooks_update_playbook_sync.py | 57 + ...ow_v3_generated_tools_create_tool_async.py | 59 + ...low_v3_generated_tools_create_tool_sync.py | 59 + ...nerated_tools_create_tool_version_async.py | 60 + ...enerated_tools_create_tool_version_sync.py | 60 + ...ow_v3_generated_tools_delete_tool_async.py | 50 + ...low_v3_generated_tools_delete_tool_sync.py | 50 + ...nerated_tools_delete_tool_version_async.py | 50 + ...enerated_tools_delete_tool_version_sync.py | 50 + ...gflow_v3_generated_tools_get_tool_async.py | 53 + ...ogflow_v3_generated_tools_get_tool_sync.py | 53 + ..._generated_tools_get_tool_version_async.py | 53 + ...3_generated_tools_get_tool_version_sync.py | 53 + ...enerated_tools_list_tool_versions_async.py | 54 + ...generated_tools_list_tool_versions_sync.py | 54 + ...low_v3_generated_tools_list_tools_async.py | 54 + ...flow_v3_generated_tools_list_tools_sync.py | 54 + ...erated_tools_restore_tool_version_async.py | 53 + ...nerated_tools_restore_tool_version_sync.py | 53 + ...ow_v3_generated_tools_update_tool_async.py | 58 + ...low_v3_generated_tools_update_tool_sync.py | 58 + ...etadata_google.cloud.dialogflow.cx.v3.json | 9185 ++++++++--- .../unit/gapic/dialogflowcx_v3/test_agents.py | 116 +- .../dialogflowcx_v3/test_environments.py | 150 +- .../gapic/dialogflowcx_v3/test_examples.py | 7280 +++++++++ .../unit/gapic/dialogflowcx_v3/test_flows.py | 160 +- .../gapic/dialogflowcx_v3/test_generators.py | 9 + .../unit/gapic/dialogflowcx_v3/test_pages.py | 130 +- .../gapic/dialogflowcx_v3/test_playbooks.py | 13060 ++++++++++++++++ .../gapic/dialogflowcx_v3/test_sessions.py | 174 +- .../gapic/dialogflowcx_v3/test_test_cases.py | 181 +- .../unit/gapic/dialogflowcx_v3/test_tools.py | 11186 +++++++++++++ .../test_transition_route_groups.py | 98 +- .../gapic/dialogflowcx_v3/test_webhooks.py | 90 +- .../docs/kms_v1/hsm_management.rst | 10 + .../docs/kms_v1/services_.rst | 1 + .../google/cloud/kms/__init__.py | 48 + .../google/cloud/kms_v1/__init__.py | 45 + .../google/cloud/kms_v1/gapic_metadata.json | 154 + .../services/hsm_management/__init__.py | 22 + .../services/hsm_management/async_client.py | 2056 +++ .../kms_v1/services/hsm_management/client.py | 2528 +++ .../kms_v1/services/hsm_management/pagers.py | 371 + .../hsm_management/transports/README.rst | 9 + .../hsm_management/transports/__init__.py | 36 + .../hsm_management/transports/base.py | 486 + .../hsm_management/transports/grpc.py | 803 + .../hsm_management/transports/grpc_asyncio.py | 988 ++ .../hsm_management/transports/rest.py | 3246 ++++ .../hsm_management/transports/rest_base.py | 789 + .../key_management_service/async_client.py | 2 +- .../services/key_management_service/client.py | 2 +- .../google/cloud/kms_v1/types/__init__.py | 42 + .../cloud/kms_v1/types/hsm_management.py | 1297 ++ .../google/cloud/kms_v1/types/resources.py | 29 +- .../google/cloud/kms_v1/types/service.py | 10 + ...ngle_tenant_hsm_instance_proposal_async.py | 58 + ...ingle_tenant_hsm_instance_proposal_sync.py | 58 + ...create_single_tenant_hsm_instance_async.py | 61 + ...ngle_tenant_hsm_instance_proposal_async.py | 67 + ...ingle_tenant_hsm_instance_proposal_sync.py | 67 + ..._create_single_tenant_hsm_instance_sync.py | 61 + ...ngle_tenant_hsm_instance_proposal_async.py | 50 + ...ingle_tenant_hsm_instance_proposal_sync.py | 50 + ...ngle_tenant_hsm_instance_proposal_async.py | 57 + ...ingle_tenant_hsm_instance_proposal_sync.py | 57 + ...nt_get_single_tenant_hsm_instance_async.py | 53 + ...ngle_tenant_hsm_instance_proposal_async.py | 53 + ...ingle_tenant_hsm_instance_proposal_sync.py | 53 + ...ent_get_single_tenant_hsm_instance_sync.py | 53 + ...gle_tenant_hsm_instance_proposals_async.py | 54 + ...ngle_tenant_hsm_instance_proposals_sync.py | 54 + ..._list_single_tenant_hsm_instances_async.py | 54 + ...t_list_single_tenant_hsm_instances_sync.py | 54 + ...agement_service_create_import_job_async.py | 2 +- ...nagement_service_create_import_job_sync.py | 2 +- .../snippet_metadata_google.cloud.kms.v1.json | 1483 ++ .../unit/gapic/kms_v1/test_hsm_management.py | 11292 +++++++++++++ .../kms_v1/test_key_management_service.py | 15 + .../types/internal_range.py | 19 +- .../docs/run_v2/instances.rst | 10 + .../docs/run_v2/services_.rst | 1 + .../google/cloud/run/__init__.py | 24 + .../google/cloud/run_v2/__init__.py | 23 + .../google/cloud/run_v2/gapic_metadata.json | 109 + .../run_v2/services/instances/__init__.py | 22 + .../run_v2/services/instances/async_client.py | 1329 ++ .../cloud/run_v2/services/instances/client.py | 1861 +++ .../cloud/run_v2/services/instances/pagers.py | 197 + .../services/instances/transports/README.rst | 9 + .../services/instances/transports/__init__.py | 36 + .../services/instances/transports/base.py | 302 + .../services/instances/transports/grpc.py | 580 + .../instances/transports/grpc_asyncio.py | 654 + .../services/instances/transports/rest.py | 2181 +++ .../instances/transports/rest_base.py | 514 + .../google/cloud/run_v2/types/__init__.py | 20 + .../cloud/run_v2/types/container_status.py | 55 + .../google/cloud/run_v2/types/instance.py | 597 + .../google/cloud/run_v2/types/k8s_min.py | 7 + ...nerated_instances_create_instance_async.py | 62 + ...enerated_instances_create_instance_sync.py | 62 + ...nerated_instances_delete_instance_async.py | 57 + ...enerated_instances_delete_instance_sync.py | 57 + ..._generated_instances_get_instance_async.py | 53 + ...2_generated_instances_get_instance_sync.py | 53 + ...enerated_instances_list_instances_async.py | 54 + ...generated_instances_list_instances_sync.py | 54 + ...enerated_instances_start_instance_async.py | 57 + ...generated_instances_start_instance_sync.py | 57 + ...generated_instances_stop_instance_async.py | 57 + ..._generated_instances_stop_instance_sync.py | 57 + .../snippet_metadata_google.cloud.run.v2.json | 974 ++ .../tests/unit/gapic/run_v2/test_instances.py | 8059 ++++++++++ .../tests/unit/gapic/run_v2/test_jobs.py | 2 + .../tests/unit/gapic/run_v2/test_services.py | 2 + .../unit/gapic/run_v2/test_worker_pools.py | 2 + 251 files changed, 121928 insertions(+), 2802 deletions(-) create mode 100644 packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py create mode 100644 packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/examples.rst create mode 100644 packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/playbooks.rst create mode 100644 packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/tools.rst create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/async_client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/pagers.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/README.rst create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest_base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/async_client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/pagers.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/README.rst create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest_base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/async_client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/client.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/pagers.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/README.rst create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/__init__.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest_base.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/code_block.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/example.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/parameter_definition.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/playbook.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool_call.py create mode 100644 packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/trace.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_async.py create mode 100644 packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_sync.py create mode 100644 packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_examples.py create mode 100644 packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_playbooks.py create mode 100644 packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_tools.py create mode 100644 packages/google-cloud-kms/docs/kms_v1/hsm_management.rst create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/__init__.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/async_client.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/client.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/pagers.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/README.rst create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/__init__.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/base.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest_base.py create mode 100644 packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py create mode 100644 packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py create mode 100644 packages/google-cloud-run/docs/run_v2/instances.rst create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/__init__.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/async_client.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/client.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/pagers.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/README.rst create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/__init__.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/base.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest_base.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/types/container_status.py create mode 100644 packages/google-cloud-run/google/cloud/run_v2/types/instance.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_sync.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_sync.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_sync.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_sync.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_sync.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_async.py create mode 100644 packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_sync.py create mode 100644 packages/google-cloud-run/tests/unit/gapic/run_v2/test_instances.py diff --git a/.librarian/state.yaml b/.librarian/state.yaml index 37c09bf40d41..32c3e92fbe2a 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -19,7 +19,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-ads-datamanager version: 0.3.0 - last_generated_commit: c2db528a3e4d12b95666c719ee0db30a3d4c78ad + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/ads/datamanager/v1 service_config: datamanager_v1.yaml @@ -1344,7 +1344,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-databasecenter version: 0.3.0 - last_generated_commit: 94aa4f5ae672addf00e7970ecc47699e34989e90 + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/databasecenter/v1beta service_config: databasecenter_v1beta.yaml @@ -1595,7 +1595,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dialogflow-cx version: 2.2.0 - last_generated_commit: 9a477cd3c26a704130e2a2fb44a40281d9312e4c + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/dialogflow/cx/v3 service_config: dialogflow_v3.yaml @@ -2104,7 +2104,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-kms version: 3.9.0 - last_generated_commit: 94aa4f5ae672addf00e7970ecc47699e34989e90 + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/kms/v1 service_config: cloudkms_v1.yaml @@ -2463,7 +2463,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-network-connectivity version: 2.12.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/networkconnectivity/v1 service_config: networkconnectivity_v1.yaml @@ -2993,7 +2993,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-run version: 0.14.0 - last_generated_commit: 94aa4f5ae672addf00e7970ecc47699e34989e90 + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/run/v2 service_config: run_v2.yaml @@ -3751,7 +3751,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-workflows version: 1.20.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/cloud/workflows/executions/v1 service_config: workflowexecutions_v1.yaml @@ -4264,7 +4264,7 @@ libraries: tag_format: '{id}-v{version}' - id: googleapis-common-protos version: 1.72.0 - last_generated_commit: 94aa4f5ae672addf00e7970ecc47699e34989e90 + last_generated_commit: 87e3579c041a50f985f8de71e9494c8fc85d520b apis: - path: google/api service_config: serviceconfig.yaml diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py index 99765a516a64..c28dd875e06f 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py @@ -48,12 +48,16 @@ AggregateFleetRequest, AggregateFleetResponse, AggregateFleetRow, + AggregateIssueStatsRequest, + AggregateIssueStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, DeltaDetails, Dimension, Edition, + IssueGroupStats, + IssueStats, Label, ManagementType, QueryDatabaseResourceGroupsRequest, @@ -109,11 +113,15 @@ "AggregateFleetRequest", "AggregateFleetResponse", "AggregateFleetRow", + "AggregateIssueStatsRequest", + "AggregateIssueStatsResponse", "BackupDRConfig", "DatabaseResource", "DatabaseResourceGroup", "DeltaDetails", "Dimension", + "IssueGroupStats", + "IssueStats", "Label", "QueryDatabaseResourceGroupsRequest", "QueryDatabaseResourceGroupsResponse", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py index 4b97d7f5e756..bcbcff00f362 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py @@ -43,12 +43,16 @@ AggregateFleetRequest, AggregateFleetResponse, AggregateFleetRow, + AggregateIssueStatsRequest, + AggregateIssueStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, DeltaDetails, Dimension, Edition, + IssueGroupStats, + IssueStats, Label, ManagementType, QueryDatabaseResourceGroupsRequest, @@ -186,6 +190,8 @@ def _get_version(dependency_name): "AggregateFleetRequest", "AggregateFleetResponse", "AggregateFleetRow", + "AggregateIssueStatsRequest", + "AggregateIssueStatsResponse", "AutomatedBackupPolicyInfo", "BackupDRConfig", "BackupRunInfo", @@ -199,7 +205,9 @@ def _get_version(dependency_name): "Engine", "InefficientQueryInfo", "IssueCount", + "IssueGroupStats", "IssueSeverity", + "IssueStats", "Label", "MachineConfig", "MaintenanceInfo", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json index 06e0d17036fb..2046470f4d34 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json @@ -15,6 +15,11 @@ "aggregate_fleet" ] }, + "AggregateIssueStats": { + "methods": [ + "aggregate_issue_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" @@ -35,6 +40,11 @@ "aggregate_fleet" ] }, + "AggregateIssueStats": { + "methods": [ + "aggregate_issue_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" @@ -55,6 +65,11 @@ "aggregate_fleet" ] }, + "AggregateIssueStats": { + "methods": [ + "aggregate_issue_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py index 590e9d24d035..53fd9b15050c 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py @@ -580,6 +580,89 @@ async def sample_query_database_resource_groups(): # Done; return the response. return response + async def aggregate_issue_stats( + self, + request: Optional[Union[service.AggregateIssueStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.AggregateIssueStatsResponse: + r"""AggregateIssueStats provides database resource issues + statistics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import databasecenter_v1beta + + async def sample_aggregate_issue_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterAsyncClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateIssueStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.aggregate_issue_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.databasecenter_v1beta.types.AggregateIssueStatsRequest, dict]]): + The request object. AggregateIssueStatsRequest represents + the input to the AggregateIssueStats + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.databasecenter_v1beta.types.AggregateIssueStatsResponse: + The response message containing one + of more group of relevant health issues + for database resources. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AggregateIssueStatsRequest): + request = service.AggregateIssueStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.aggregate_issue_stats + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "DatabaseCenterAsyncClient": return self diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py index dc1195a9a103..44c83e0a2e7b 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py @@ -997,6 +997,87 @@ def sample_query_database_resource_groups(): # Done; return the response. return response + def aggregate_issue_stats( + self, + request: Optional[Union[service.AggregateIssueStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.AggregateIssueStatsResponse: + r"""AggregateIssueStats provides database resource issues + statistics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import databasecenter_v1beta + + def sample_aggregate_issue_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateIssueStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.aggregate_issue_stats(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.databasecenter_v1beta.types.AggregateIssueStatsRequest, dict]): + The request object. AggregateIssueStatsRequest represents + the input to the AggregateIssueStats + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.databasecenter_v1beta.types.AggregateIssueStatsResponse: + The response message containing one + of more group of relevant health issues + for database resources. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AggregateIssueStatsRequest): + request = service.AggregateIssueStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.aggregate_issue_stats] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "DatabaseCenterClient": return self diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py index 07a22b06b820..8011c7e00173 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py @@ -148,6 +148,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.aggregate_issue_stats: gapic_v1.method.wrap_method( + self.aggregate_issue_stats, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -191,6 +196,18 @@ def query_database_resource_groups( ]: raise NotImplementedError() + @property + def aggregate_issue_stats( + self, + ) -> Callable[ + [service.AggregateIssueStatsRequest], + Union[ + service.AggregateIssueStatsResponse, + Awaitable[service.AggregateIssueStatsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py index dac449683c5a..a19159d5d49f 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py @@ -408,6 +408,35 @@ def query_database_resource_groups( ) return self._stubs["query_database_resource_groups"] + @property + def aggregate_issue_stats( + self, + ) -> Callable[ + [service.AggregateIssueStatsRequest], service.AggregateIssueStatsResponse + ]: + r"""Return a callable for the aggregate issue stats method over gRPC. + + AggregateIssueStats provides database resource issues + statistics. + + Returns: + Callable[[~.AggregateIssueStatsRequest], + ~.AggregateIssueStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "aggregate_issue_stats" not in self._stubs: + self._stubs["aggregate_issue_stats"] = self._logged_channel.unary_unary( + "/google.cloud.databasecenter.v1beta.DatabaseCenter/AggregateIssueStats", + request_serializer=service.AggregateIssueStatsRequest.serialize, + response_deserializer=service.AggregateIssueStatsResponse.deserialize, + ) + return self._stubs["aggregate_issue_stats"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py index 6003afa9b3e3..8051818e3a2d 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py @@ -420,6 +420,36 @@ def query_database_resource_groups( ) return self._stubs["query_database_resource_groups"] + @property + def aggregate_issue_stats( + self, + ) -> Callable[ + [service.AggregateIssueStatsRequest], + Awaitable[service.AggregateIssueStatsResponse], + ]: + r"""Return a callable for the aggregate issue stats method over gRPC. + + AggregateIssueStats provides database resource issues + statistics. + + Returns: + Callable[[~.AggregateIssueStatsRequest], + Awaitable[~.AggregateIssueStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "aggregate_issue_stats" not in self._stubs: + self._stubs["aggregate_issue_stats"] = self._logged_channel.unary_unary( + "/google.cloud.databasecenter.v1beta.DatabaseCenter/AggregateIssueStats", + request_serializer=service.AggregateIssueStatsRequest.serialize, + response_deserializer=service.AggregateIssueStatsResponse.deserialize, + ) + return self._stubs["aggregate_issue_stats"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -438,6 +468,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.aggregate_issue_stats: self._wrap_method( + self.aggregate_issue_stats, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py index e84fca4f1901..36260f8f8b84 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py @@ -80,6 +80,14 @@ def post_aggregate_fleet(self, response): logging.log(f"Received response: {response}") return response + def pre_aggregate_issue_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_aggregate_issue_stats(self, response): + logging.log(f"Received response: {response}") + return response + def pre_query_database_resource_groups(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -148,6 +156,56 @@ def post_aggregate_fleet_with_metadata( """ return response, metadata + def pre_aggregate_issue_stats( + self, + request: service.AggregateIssueStatsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.AggregateIssueStatsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for aggregate_issue_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the DatabaseCenter server. + """ + return request, metadata + + def post_aggregate_issue_stats( + self, response: service.AggregateIssueStatsResponse + ) -> service.AggregateIssueStatsResponse: + """Post-rpc interceptor for aggregate_issue_stats + + DEPRECATED. Please use the `post_aggregate_issue_stats_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DatabaseCenter server but before + it is returned to user code. This `post_aggregate_issue_stats` interceptor runs + before the `post_aggregate_issue_stats_with_metadata` interceptor. + """ + return response + + def post_aggregate_issue_stats_with_metadata( + self, + response: service.AggregateIssueStatsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.AggregateIssueStatsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for aggregate_issue_stats + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DatabaseCenter server but before it is returned to user code. + + We recommend only using this `post_aggregate_issue_stats_with_metadata` + interceptor in new development instead of the `post_aggregate_issue_stats` interceptor. + When both interceptors are used, this `post_aggregate_issue_stats_with_metadata` interceptor runs after the + `post_aggregate_issue_stats` interceptor. The (possibly modified) response returned by + `post_aggregate_issue_stats` will be passed to + `post_aggregate_issue_stats_with_metadata`. + """ + return response, metadata + def pre_query_database_resource_groups( self, request: service.QueryDatabaseResourceGroupsRequest, @@ -482,6 +540,166 @@ def __call__( ) return resp + class _AggregateIssueStats( + _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats, + DatabaseCenterRestStub, + ): + def __hash__(self): + return hash("DatabaseCenterRestTransport.AggregateIssueStats") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.AggregateIssueStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.AggregateIssueStatsResponse: + r"""Call the aggregate issue stats method over HTTP. + + Args: + request (~.service.AggregateIssueStatsRequest): + The request object. AggregateIssueStatsRequest represents + the input to the AggregateIssueStats + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.AggregateIssueStatsResponse: + The response message containing one + of more group of relevant health issues + for database resources. + + """ + + http_options = ( + _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats._get_http_options() + ) + + request, metadata = self._interceptor.pre_aggregate_issue_stats( + request, metadata + ) + transcoded_request = _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats._get_transcoded_request( + http_options, request + ) + + body = _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.databasecenter_v1beta.DatabaseCenterClient.AggregateIssueStats", + extra={ + "serviceName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "rpcName": "AggregateIssueStats", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DatabaseCenterRestTransport._AggregateIssueStats._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.AggregateIssueStatsResponse() + pb_resp = service.AggregateIssueStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_aggregate_issue_stats(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_aggregate_issue_stats_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.AggregateIssueStatsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.databasecenter_v1beta.DatabaseCenterClient.aggregate_issue_stats", + extra={ + "serviceName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "rpcName": "AggregateIssueStats", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _QueryDatabaseResourceGroups( _BaseDatabaseCenterRestTransport._BaseQueryDatabaseResourceGroups, DatabaseCenterRestStub, @@ -803,6 +1021,16 @@ def aggregate_fleet( # In C++ this would require a dynamic_cast return self._AggregateFleet(self._session, self._host, self._interceptor) # type: ignore + @property + def aggregate_issue_stats( + self, + ) -> Callable[ + [service.AggregateIssueStatsRequest], service.AggregateIssueStatsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AggregateIssueStats(self._session, self._host, self._interceptor) # type: ignore + @property def query_database_resource_groups( self, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py index 866692542068..e1f89ef87e47 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py @@ -136,6 +136,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseAggregateIssueStats: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta:aggregateIssueStats", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.AggregateIssueStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseDatabaseCenterRestTransport._BaseAggregateIssueStats._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseQueryDatabaseResourceGroups: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py index 6e85318d18da..632dda18bbe0 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py @@ -27,12 +27,16 @@ AggregateFleetRequest, AggregateFleetResponse, AggregateFleetRow, + AggregateIssueStatsRequest, + AggregateIssueStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, DeltaDetails, Dimension, Edition, + IssueGroupStats, + IssueStats, Label, ManagementType, QueryDatabaseResourceGroupsRequest, @@ -86,11 +90,15 @@ "AggregateFleetRequest", "AggregateFleetResponse", "AggregateFleetRow", + "AggregateIssueStatsRequest", + "AggregateIssueStatsResponse", "BackupDRConfig", "DatabaseResource", "DatabaseResourceGroup", "DeltaDetails", "Dimension", + "IssueGroupStats", + "IssueStats", "Label", "QueryDatabaseResourceGroupsRequest", "QueryDatabaseResourceGroupsResponse", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/machine_config.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/machine_config.py index d05bf8b2074f..95d79852ce8c 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/machine_config.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/machine_config.py @@ -30,7 +30,6 @@ class MachineConfig(proto.Message): r"""MachineConfig describes the configuration of a machine specific to a Database Resource. - NextID: 5 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py index 62cb926d1718..1317eb5c032b 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py @@ -40,6 +40,10 @@ "QueryDatabaseResourceGroupsResponse", "DatabaseResourceGroup", "DatabaseResource", + "AggregateIssueStatsRequest", + "AggregateIssueStatsResponse", + "IssueGroupStats", + "IssueStats", "Label", "AggregateFleetRequest", "AggregateFleetResponse", @@ -595,6 +599,221 @@ class DatabaseResource(proto.Message): ) +class AggregateIssueStatsRequest(proto.Message): + r"""AggregateIssueStatsRequest represents the input to the + AggregateIssueStats method. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Parent can be a project, a folder, or an + organization. The search is limited to the resources within + the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + filter (str): + Optional. The expression to filter resources. + + Supported fields are: ``full_resource_name``, + ``resource_type``, ``container``, ``product.type``, + ``product.engine``, ``product.version``, ``location``, + ``labels``, ``issues``, fields of availability_info, + data_protection_info,'resource_name', etc. + + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. When + ``AND`` and ``OR`` are both used in the expression, + parentheses must be appropriately used to group the + combinations. + + Example: location="us-east1" Example: + container="projects/123" OR container="projects/456" + Example: (container="projects/123" OR + container="projects/456") AND location="us-east1". + signal_type_groups (MutableSequence[google.cloud.databasecenter_v1beta.types.SignalTypeGroup]): + Optional. Lists of signal types that are + issues. + baseline_date (google.type.date_pb2.Date): + Optional. The baseline date w.r.t. which the + delta counts are calculated. If not set, delta + counts are not included in the response and the + response indicates the current state of the + fleet. + + This field is a member of `oneof`_ ``_baseline_date``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + signal_type_groups: MutableSequence[signals.SignalTypeGroup] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=signals.SignalTypeGroup, + ) + baseline_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=date_pb2.Date, + ) + + +class AggregateIssueStatsResponse(proto.Message): + r"""The response message containing one of more group of relevant + health issues for database resources. + + Attributes: + issue_group_stats (MutableSequence[google.cloud.databasecenter_v1beta.types.IssueGroupStats]): + List of issue group stats where each group + contains stats for resources having a particular + combination of relevant issues. + total_resources_count (int): + Total count of the resources filtered in + based on the user given filter. + total_resource_groups_count (int): + Total count of the resource filtered in based + on the user given filter. + unreachable (MutableSequence[str]): + Unordered list. List of unreachable regions + from where data could not be retrieved. + """ + + issue_group_stats: MutableSequence["IssueGroupStats"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IssueGroupStats", + ) + total_resources_count: int = proto.Field( + proto.INT32, + number=2, + ) + total_resource_groups_count: int = proto.Field( + proto.INT32, + number=3, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class IssueGroupStats(proto.Message): + r"""IssueGroupStats refers to stats for a particulare combination + of relevant health issues of database resources. + + Attributes: + display_name (str): + Database resource level health card name. + This will corresponds to one of the requested + input group names. + resource_groups_count (int): + Total count of the groups of resources + returned by the filter that also have one or + more resources for which any of the specified + issues are applicable. + resources_count (int): + Total count of resources returned by the + filter for which any of the specified issues are + applicable. + healthy_resource_groups_count (int): + The number of resource groups from the total + groups as defined above that are healthy with + respect to all of the specified issues. + healthy_resources_count (int): + The number of resources from the total defined above in + field total_resources_count that are healthy with respect to + all of the specified issues. + issue_stats (MutableSequence[google.cloud.databasecenter_v1beta.types.IssueStats]): + List of issues stats containing count of + resources having particular issue category. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_groups_count: int = proto.Field( + proto.INT32, + number=2, + ) + resources_count: int = proto.Field( + proto.INT32, + number=3, + ) + healthy_resource_groups_count: int = proto.Field( + proto.INT32, + number=4, + ) + healthy_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + issue_stats: MutableSequence["IssueStats"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="IssueStats", + ) + + +class IssueStats(proto.Message): + r"""IssueStats holds stats for a particular signal category. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + signal_type (google.cloud.databasecenter_v1beta.types.SignalType): + Type of signal which is an issue. + resource_count (int): + Number of resources having issues of a given + type. + delta_details (google.cloud.databasecenter_v1beta.types.DeltaDetails): + Optional. Delta counts and details of + resources for which issue was raised or fixed. + + This field is a member of `oneof`_ ``_delta_details``. + issue_severity (google.cloud.databasecenter_v1beta.types.IssueSeverity): + Severity of the issue. + + This field is a member of `oneof`_ ``_issue_severity``. + """ + + signal_type: signals.SignalType = proto.Field( + proto.ENUM, + number=1, + enum=signals.SignalType, + ) + resource_count: int = proto.Field( + proto.INT32, + number=2, + ) + delta_details: "DeltaDetails" = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message="DeltaDetails", + ) + issue_severity: signals.IssueSeverity = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=signals.IssueSeverity, + ) + + class Label(proto.Message): r"""Label is a key value pair applied to a resource. diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py new file mode 100644 index 000000000000..4cac07c4dcf9 --- /dev/null +++ b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregateIssueStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-databasecenter + + +# [START databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import databasecenter_v1beta + + +async def sample_aggregate_issue_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterAsyncClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateIssueStatsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.aggregate_issue_stats(request=request) + + # Handle the response + print(response) + + +# [END databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_async] diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py new file mode 100644 index 000000000000..69bcf44ed1be --- /dev/null +++ b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregateIssueStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-databasecenter + + +# [START databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import databasecenter_v1beta + + +def sample_aggregate_issue_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateIssueStatsRequest( + parent="parent_value", + ) + + # Make the request + response = client.aggregate_issue_stats(request=request) + + # Handle the response + print(response) + + +# [END databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_sync] diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json b/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json index faa8020bc09f..4dceaaa20f80 100644 --- a/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json +++ b/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json @@ -164,6 +164,159 @@ ], "title": "databasecenter_v1beta_generated_database_center_aggregate_fleet_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterAsyncClient", + "shortName": "DatabaseCenterAsyncClient" + }, + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterAsyncClient.aggregate_issue_stats", + "method": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter.AggregateIssueStats", + "service": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "shortName": "DatabaseCenter" + }, + "shortName": "AggregateIssueStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.databasecenter_v1beta.types.AggregateIssueStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.databasecenter_v1beta.types.AggregateIssueStatsResponse", + "shortName": "aggregate_issue_stats" + }, + "description": "Sample for AggregateIssueStats", + "file": "databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "databasecenter_v1beta_generated_database_center_aggregate_issue_stats_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterClient", + "shortName": "DatabaseCenterClient" + }, + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterClient.aggregate_issue_stats", + "method": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter.AggregateIssueStats", + "service": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "shortName": "DatabaseCenter" + }, + "shortName": "AggregateIssueStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.databasecenter_v1beta.types.AggregateIssueStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.databasecenter_v1beta.types.AggregateIssueStatsResponse", + "shortName": "aggregate_issue_stats" + }, + "description": "Sample for AggregateIssueStats", + "file": "databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "databasecenter_v1beta_generated_DatabaseCenter_AggregateIssueStats_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py b/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py index 73c7688b59be..55d66d69dbf9 100644 --- a/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py +++ b/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py @@ -2478,6 +2478,207 @@ async def test_query_database_resource_groups_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + service.AggregateIssueStatsRequest, + dict, + ], +) +def test_aggregate_issue_stats(request_type, transport: str = "grpc"): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AggregateIssueStatsResponse( + total_resources_count=2278, + total_resource_groups_count=2930, + unreachable=["unreachable_value"], + ) + response = client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.AggregateIssueStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AggregateIssueStatsResponse) + assert response.total_resources_count == 2278 + assert response.total_resource_groups_count == 2930 + assert response.unreachable == ["unreachable_value"] + + +def test_aggregate_issue_stats_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.AggregateIssueStatsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.aggregate_issue_stats(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AggregateIssueStatsRequest( + parent="parent_value", + filter="filter_value", + ) + + +def test_aggregate_issue_stats_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.aggregate_issue_stats + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.aggregate_issue_stats + ] = mock_rpc + request = {} + client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.aggregate_issue_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_aggregate_issue_stats_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.aggregate_issue_stats + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.aggregate_issue_stats + ] = mock_rpc + + request = {} + await client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.aggregate_issue_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_aggregate_issue_stats_async( + transport: str = "grpc_asyncio", request_type=service.AggregateIssueStatsRequest +): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AggregateIssueStatsResponse( + total_resources_count=2278, + total_resource_groups_count=2930, + unreachable=["unreachable_value"], + ) + ) + response = await client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.AggregateIssueStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AggregateIssueStatsResponse) + assert response.total_resources_count == 2278 + assert response.total_resource_groups_count == 2930 + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_aggregate_issue_stats_async_from_dict(): + await test_aggregate_issue_stats_async(request_type=dict) + + def test_query_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3091,6 +3292,132 @@ def test_query_database_resource_groups_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token +def test_aggregate_issue_stats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.aggregate_issue_stats + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.aggregate_issue_stats + ] = mock_rpc + + request = {} + client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.aggregate_issue_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_aggregate_issue_stats_rest_required_fields( + request_type=service.AggregateIssueStatsRequest, +): + transport_class = transports.DatabaseCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AggregateIssueStatsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AggregateIssueStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.aggregate_issue_stats(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_aggregate_issue_stats_rest_unset_required_fields(): + transport = transports.DatabaseCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.aggregate_issue_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DatabaseCenterGrpcTransport( @@ -3262,6 +3589,29 @@ def test_query_database_resource_groups_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_aggregate_issue_stats_empty_call_grpc(): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + call.return_value = service.AggregateIssueStatsResponse() + client.aggregate_issue_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateIssueStatsRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = DatabaseCenterAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -3364,6 +3714,37 @@ async def test_query_database_resource_groups_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_aggregate_issue_stats_empty_call_grpc_asyncio(): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AggregateIssueStatsResponse( + total_resources_count=2278, + total_resource_groups_count=2930, + unreachable=["unreachable_value"], + ) + ) + await client.aggregate_issue_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateIssueStatsRequest() + + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = DatabaseCenterClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -3764,6 +4145,143 @@ def test_query_database_resource_groups_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_aggregate_issue_stats_rest_bad_request( + request_type=service.AggregateIssueStatsRequest, +): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.aggregate_issue_stats(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.AggregateIssueStatsRequest, + dict, + ], +) +def test_aggregate_issue_stats_rest_call_success(request_type): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AggregateIssueStatsResponse( + total_resources_count=2278, + total_resource_groups_count=2930, + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AggregateIssueStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.aggregate_issue_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AggregateIssueStatsResponse) + assert response.total_resources_count == 2278 + assert response.total_resource_groups_count == 2930 + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregate_issue_stats_rest_interceptors(null_interceptor): + transport = transports.DatabaseCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DatabaseCenterRestInterceptor(), + ) + client = DatabaseCenterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DatabaseCenterRestInterceptor, "post_aggregate_issue_stats" + ) as post, mock.patch.object( + transports.DatabaseCenterRestInterceptor, + "post_aggregate_issue_stats_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.DatabaseCenterRestInterceptor, "pre_aggregate_issue_stats" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.AggregateIssueStatsRequest.pb( + service.AggregateIssueStatsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.AggregateIssueStatsResponse.to_json( + service.AggregateIssueStatsResponse() + ) + req.return_value.content = return_value + + request = service.AggregateIssueStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AggregateIssueStatsResponse() + post_with_metadata.return_value = ( + service.AggregateIssueStatsResponse(), + metadata, + ) + + client.aggregate_issue_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_initialize_client_w_rest(): client = DatabaseCenterClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -3833,6 +4351,28 @@ def test_query_database_resource_groups_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_aggregate_issue_stats_empty_call_rest(): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_issue_stats), "__call__" + ) as call: + client.aggregate_issue_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateIssueStatsRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = DatabaseCenterClient( @@ -3869,6 +4409,7 @@ def test_database_center_base_transport(): "query_products", "aggregate_fleet", "query_database_resource_groups", + "aggregate_issue_stats", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4136,6 +4677,9 @@ def test_database_center_client_transport_session_collision(transport_name): session1 = client1.transport.query_database_resource_groups._session session2 = client2.transport.query_database_resource_groups._session assert session1 != session2 + session1 = client1.transport.aggregate_issue_stats._session + session2 = client2.transport.aggregate_issue_stats._session + assert session1 != session2 def test_database_center_grpc_transport_channel(): diff --git a/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/examples.rst b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/examples.rst new file mode 100644 index 000000000000..be204bbda928 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/examples.rst @@ -0,0 +1,10 @@ +Examples +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.examples + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.examples.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/playbooks.rst b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/playbooks.rst new file mode 100644 index 000000000000..862fee5eba7e --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/playbooks.rst @@ -0,0 +1,10 @@ +Playbooks +--------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.playbooks + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.playbooks.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/services_.rst b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/services_.rst index 58869ddd8008..d6c7373226d1 100644 --- a/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/services_.rst +++ b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/services_.rst @@ -8,15 +8,18 @@ Services for Google Cloud Dialogflowcx v3 API deployments entity_types environments + examples experiments flows generators intents pages + playbooks security_settings_service session_entity_types sessions test_cases + tools transition_route_groups versions webhooks diff --git a/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/tools.rst b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/tools.rst new file mode 100644 index 000000000000..359752a3d60b --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/docs/dialogflowcx_v3/tools.rst @@ -0,0 +1,10 @@ +Tools +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.tools + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.tools.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py index 090b5389a25d..fb3635231377 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/__init__.py @@ -36,6 +36,10 @@ EnvironmentsAsyncClient, ) from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.examples.async_client import ( + ExamplesAsyncClient, +) +from google.cloud.dialogflowcx_v3.services.examples.client import ExamplesClient from google.cloud.dialogflowcx_v3.services.experiments.async_client import ( ExperimentsAsyncClient, ) @@ -52,6 +56,10 @@ from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient from google.cloud.dialogflowcx_v3.services.pages.client import PagesClient +from google.cloud.dialogflowcx_v3.services.playbooks.async_client import ( + PlaybooksAsyncClient, +) +from google.cloud.dialogflowcx_v3.services.playbooks.client import PlaybooksClient from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import ( SecuritySettingsServiceAsyncClient, ) @@ -72,6 +80,8 @@ TestCasesAsyncClient, ) from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient +from google.cloud.dialogflowcx_v3.services.tools.async_client import ToolsAsyncClient +from google.cloud.dialogflowcx_v3.services.tools.client import ToolsClient from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import ( TransitionRouteGroupsAsyncClient, ) @@ -124,6 +134,7 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from google.cloud.dialogflowcx_v3.types.code_block import CodeBlock from google.cloud.dialogflowcx_v3.types.data_store_connection import ( DataStoreConnection, DataStoreConnectionSignals, @@ -171,6 +182,15 @@ RunContinuousTestResponse, UpdateEnvironmentRequest, ) +from google.cloud.dialogflowcx_v3.types.example import ( + CreateExampleRequest, + DeleteExampleRequest, + Example, + GetExampleRequest, + ListExamplesRequest, + ListExamplesResponse, + UpdateExampleRequest, +) from google.cloud.dialogflowcx_v3.types.experiment import ( CreateExperimentRequest, DeleteExperimentRequest, @@ -207,7 +227,10 @@ ) from google.cloud.dialogflowcx_v3.types.fulfillment import Fulfillment from google.cloud.dialogflowcx_v3.types.gcs import GcsDestination -from google.cloud.dialogflowcx_v3.types.generative_settings import GenerativeSettings +from google.cloud.dialogflowcx_v3.types.generative_settings import ( + GenerativeSettings, + LlmModelSettings, +) from google.cloud.dialogflowcx_v3.types.generator import ( CreateGeneratorRequest, DeleteGeneratorRequest, @@ -249,6 +272,35 @@ TransitionRoute, UpdatePageRequest, ) +from google.cloud.dialogflowcx_v3.types.parameter_definition import ( + DataType, + InlineSchema, + ParameterDefinition, + TypeSchema, +) +from google.cloud.dialogflowcx_v3.types.playbook import ( + CreatePlaybookRequest, + CreatePlaybookVersionRequest, + DeletePlaybookRequest, + DeletePlaybookVersionRequest, + ExportPlaybookRequest, + ExportPlaybookResponse, + GetPlaybookRequest, + GetPlaybookVersionRequest, + Handler, + ImportPlaybookRequest, + ImportPlaybookResponse, + ListPlaybooksRequest, + ListPlaybooksResponse, + ListPlaybookVersionsRequest, + ListPlaybookVersionsResponse, + Playbook, + PlaybookImportStrategy, + PlaybookVersion, + RestorePlaybookVersionRequest, + RestorePlaybookVersionResponse, + UpdatePlaybookRequest, +) from google.cloud.dialogflowcx_v3.types.response_message import ResponseMessage from google.cloud.dialogflowcx_v3.types.safety_settings import SafetySettings from google.cloud.dialogflowcx_v3.types.security_settings import ( @@ -268,6 +320,7 @@ CloudConversationDebuggingInfo, DetectIntentRequest, DetectIntentResponse, + DetectIntentResponseView, DtmfInput, EventInput, FilterSpecs, @@ -333,6 +386,37 @@ TransitionRouteGroupCoverage, UpdateTestCaseRequest, ) +from google.cloud.dialogflowcx_v3.types.tool import ( + CreateToolRequest, + CreateToolVersionRequest, + DeleteToolRequest, + DeleteToolVersionRequest, + GetToolRequest, + GetToolVersionRequest, + ListToolsRequest, + ListToolsResponse, + ListToolVersionsRequest, + ListToolVersionsResponse, + RestoreToolVersionRequest, + RestoreToolVersionResponse, + Tool, + ToolVersion, + UpdateToolRequest, +) +from google.cloud.dialogflowcx_v3.types.tool_call import ToolCall, ToolCallResult +from google.cloud.dialogflowcx_v3.types.trace import ( + Action, + AgentUtterance, + FlowInvocation, + FlowTransition, + OutputState, + PlaybookInput, + PlaybookInvocation, + PlaybookOutput, + PlaybookTransition, + ToolUse, + UserUtterance, +) from google.cloud.dialogflowcx_v3.types.transition_route_group import ( CreateTransitionRouteGroupRequest, DeleteTransitionRouteGroupRequest, @@ -385,6 +469,8 @@ "EntityTypesAsyncClient", "EnvironmentsClient", "EnvironmentsAsyncClient", + "ExamplesClient", + "ExamplesAsyncClient", "ExperimentsClient", "ExperimentsAsyncClient", "FlowsClient", @@ -395,6 +481,8 @@ "IntentsAsyncClient", "PagesClient", "PagesAsyncClient", + "PlaybooksClient", + "PlaybooksAsyncClient", "SecuritySettingsServiceClient", "SecuritySettingsServiceAsyncClient", "SessionEntityTypesClient", @@ -403,6 +491,8 @@ "SessionsAsyncClient", "TestCasesClient", "TestCasesAsyncClient", + "ToolsClient", + "ToolsAsyncClient", "TransitionRouteGroupsClient", "TransitionRouteGroupsAsyncClient", "VersionsClient", @@ -441,6 +531,7 @@ "GetChangelogRequest", "ListChangelogsRequest", "ListChangelogsResponse", + "CodeBlock", "DataStoreConnection", "DataStoreConnectionSignals", "DataStoreType", @@ -480,6 +571,13 @@ "RunContinuousTestRequest", "RunContinuousTestResponse", "UpdateEnvironmentRequest", + "CreateExampleRequest", + "DeleteExampleRequest", + "Example", + "GetExampleRequest", + "ListExamplesRequest", + "ListExamplesResponse", + "UpdateExampleRequest", "CreateExperimentRequest", "DeleteExperimentRequest", "Experiment", @@ -513,6 +611,7 @@ "Fulfillment", "GcsDestination", "GenerativeSettings", + "LlmModelSettings", "CreateGeneratorRequest", "DeleteGeneratorRequest", "Generator", @@ -549,6 +648,31 @@ "Page", "TransitionRoute", "UpdatePageRequest", + "InlineSchema", + "ParameterDefinition", + "TypeSchema", + "DataType", + "CreatePlaybookRequest", + "CreatePlaybookVersionRequest", + "DeletePlaybookRequest", + "DeletePlaybookVersionRequest", + "ExportPlaybookRequest", + "ExportPlaybookResponse", + "GetPlaybookRequest", + "GetPlaybookVersionRequest", + "Handler", + "ImportPlaybookRequest", + "ImportPlaybookResponse", + "ListPlaybooksRequest", + "ListPlaybooksResponse", + "ListPlaybookVersionsRequest", + "ListPlaybookVersionsResponse", + "Playbook", + "PlaybookImportStrategy", + "PlaybookVersion", + "RestorePlaybookVersionRequest", + "RestorePlaybookVersionResponse", + "UpdatePlaybookRequest", "ResponseMessage", "SafetySettings", "CreateSecuritySettingsRequest", @@ -584,6 +708,7 @@ "StreamingRecognitionResult", "SubmitAnswerFeedbackRequest", "TextInput", + "DetectIntentResponseView", "CreateSessionEntityTypeRequest", "DeleteSessionEntityTypeRequest", "GetSessionEntityTypeRequest", @@ -625,6 +750,34 @@ "TransitionRouteGroupCoverage", "UpdateTestCaseRequest", "TestResult", + "CreateToolRequest", + "CreateToolVersionRequest", + "DeleteToolRequest", + "DeleteToolVersionRequest", + "GetToolRequest", + "GetToolVersionRequest", + "ListToolsRequest", + "ListToolsResponse", + "ListToolVersionsRequest", + "ListToolVersionsResponse", + "RestoreToolVersionRequest", + "RestoreToolVersionResponse", + "Tool", + "ToolVersion", + "UpdateToolRequest", + "ToolCall", + "ToolCallResult", + "Action", + "AgentUtterance", + "FlowInvocation", + "FlowTransition", + "PlaybookInput", + "PlaybookInvocation", + "PlaybookOutput", + "PlaybookTransition", + "ToolUse", + "UserUtterance", + "OutputState", "CreateTransitionRouteGroupRequest", "DeleteTransitionRouteGroupRequest", "GetTransitionRouteGroupRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py index 6112f459b6d4..ddec0d64e06c 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/__init__.py @@ -33,11 +33,13 @@ from .services.deployments import DeploymentsAsyncClient, DeploymentsClient from .services.entity_types import EntityTypesAsyncClient, EntityTypesClient from .services.environments import EnvironmentsAsyncClient, EnvironmentsClient +from .services.examples import ExamplesAsyncClient, ExamplesClient from .services.experiments import ExperimentsAsyncClient, ExperimentsClient from .services.flows import FlowsAsyncClient, FlowsClient from .services.generators import GeneratorsAsyncClient, GeneratorsClient from .services.intents import IntentsAsyncClient, IntentsClient from .services.pages import PagesAsyncClient, PagesClient +from .services.playbooks import PlaybooksAsyncClient, PlaybooksClient from .services.security_settings_service import ( SecuritySettingsServiceAsyncClient, SecuritySettingsServiceClient, @@ -48,6 +50,7 @@ ) from .services.sessions import SessionsAsyncClient, SessionsClient from .services.test_cases import TestCasesAsyncClient, TestCasesClient +from .services.tools import ToolsAsyncClient, ToolsClient from .services.transition_route_groups import ( TransitionRouteGroupsAsyncClient, TransitionRouteGroupsClient, @@ -92,6 +95,7 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from .types.code_block import CodeBlock from .types.data_store_connection import ( DataStoreConnection, DataStoreConnectionSignals, @@ -139,6 +143,15 @@ RunContinuousTestResponse, UpdateEnvironmentRequest, ) +from .types.example import ( + CreateExampleRequest, + DeleteExampleRequest, + Example, + GetExampleRequest, + ListExamplesRequest, + ListExamplesResponse, + UpdateExampleRequest, +) from .types.experiment import ( CreateExperimentRequest, DeleteExperimentRequest, @@ -175,7 +188,7 @@ ) from .types.fulfillment import Fulfillment from .types.gcs import GcsDestination -from .types.generative_settings import GenerativeSettings +from .types.generative_settings import GenerativeSettings, LlmModelSettings from .types.generator import ( CreateGeneratorRequest, DeleteGeneratorRequest, @@ -217,6 +230,35 @@ TransitionRoute, UpdatePageRequest, ) +from .types.parameter_definition import ( + DataType, + InlineSchema, + ParameterDefinition, + TypeSchema, +) +from .types.playbook import ( + CreatePlaybookRequest, + CreatePlaybookVersionRequest, + DeletePlaybookRequest, + DeletePlaybookVersionRequest, + ExportPlaybookRequest, + ExportPlaybookResponse, + GetPlaybookRequest, + GetPlaybookVersionRequest, + Handler, + ImportPlaybookRequest, + ImportPlaybookResponse, + ListPlaybooksRequest, + ListPlaybooksResponse, + ListPlaybookVersionsRequest, + ListPlaybookVersionsResponse, + Playbook, + PlaybookImportStrategy, + PlaybookVersion, + RestorePlaybookVersionRequest, + RestorePlaybookVersionResponse, + UpdatePlaybookRequest, +) from .types.response_message import ResponseMessage from .types.safety_settings import SafetySettings from .types.security_settings import ( @@ -236,6 +278,7 @@ CloudConversationDebuggingInfo, DetectIntentRequest, DetectIntentResponse, + DetectIntentResponseView, DtmfInput, EventInput, FilterSpecs, @@ -301,6 +344,37 @@ TransitionRouteGroupCoverage, UpdateTestCaseRequest, ) +from .types.tool import ( + CreateToolRequest, + CreateToolVersionRequest, + DeleteToolRequest, + DeleteToolVersionRequest, + GetToolRequest, + GetToolVersionRequest, + ListToolsRequest, + ListToolsResponse, + ListToolVersionsRequest, + ListToolVersionsResponse, + RestoreToolVersionRequest, + RestoreToolVersionResponse, + Tool, + ToolVersion, + UpdateToolRequest, +) +from .types.tool_call import ToolCall, ToolCallResult +from .types.trace import ( + Action, + AgentUtterance, + FlowInvocation, + FlowTransition, + OutputState, + PlaybookInput, + PlaybookInvocation, + PlaybookOutput, + PlaybookTransition, + ToolUse, + UserUtterance, +) from .types.transition_route_group import ( CreateTransitionRouteGroupRequest, DeleteTransitionRouteGroupRequest, @@ -439,20 +513,25 @@ def _get_version(dependency_name): "DeploymentsAsyncClient", "EntityTypesAsyncClient", "EnvironmentsAsyncClient", + "ExamplesAsyncClient", "ExperimentsAsyncClient", "FlowsAsyncClient", "GeneratorsAsyncClient", "IntentsAsyncClient", "PagesAsyncClient", + "PlaybooksAsyncClient", "SecuritySettingsServiceAsyncClient", "SessionEntityTypesAsyncClient", "SessionsAsyncClient", "TestCasesAsyncClient", + "ToolsAsyncClient", "TransitionRouteGroupsAsyncClient", "VersionsAsyncClient", "WebhooksAsyncClient", + "Action", "AdvancedSettings", "Agent", + "AgentUtterance", "AgentValidationResult", "AgentsClient", "AnswerFeedback", @@ -470,6 +549,7 @@ def _get_version(dependency_name): "Changelog", "ChangelogsClient", "CloudConversationDebuggingInfo", + "CodeBlock", "CompareVersionsRequest", "CompareVersionsResponse", "ContinuousTestResult", @@ -477,14 +557,19 @@ def _get_version(dependency_name): "CreateAgentRequest", "CreateEntityTypeRequest", "CreateEnvironmentRequest", + "CreateExampleRequest", "CreateExperimentRequest", "CreateFlowRequest", "CreateGeneratorRequest", "CreateIntentRequest", "CreatePageRequest", + "CreatePlaybookRequest", + "CreatePlaybookVersionRequest", "CreateSecuritySettingsRequest", "CreateSessionEntityTypeRequest", "CreateTestCaseRequest", + "CreateToolRequest", + "CreateToolVersionRequest", "CreateTransitionRouteGroupRequest", "CreateVersionOperationMetadata", "CreateVersionRequest", @@ -492,16 +577,22 @@ def _get_version(dependency_name): "DataStoreConnection", "DataStoreConnectionSignals", "DataStoreType", + "DataType", "DeleteAgentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", + "DeleteExampleRequest", "DeleteExperimentRequest", "DeleteFlowRequest", "DeleteGeneratorRequest", "DeleteIntentRequest", "DeletePageRequest", + "DeletePlaybookRequest", + "DeletePlaybookVersionRequest", "DeleteSecuritySettingsRequest", "DeleteSessionEntityTypeRequest", + "DeleteToolRequest", + "DeleteToolVersionRequest", "DeleteTransitionRouteGroupRequest", "DeleteVersionRequest", "DeleteWebhookRequest", @@ -512,6 +603,7 @@ def _get_version(dependency_name): "DeploymentsClient", "DetectIntentRequest", "DetectIntentResponse", + "DetectIntentResponseView", "DocumentProcessingMode", "DtmfInput", "EntityType", @@ -520,6 +612,8 @@ def _get_version(dependency_name): "EnvironmentsClient", "EventHandler", "EventInput", + "Example", + "ExamplesClient", "Experiment", "ExperimentsClient", "ExportAgentRequest", @@ -532,12 +626,16 @@ def _get_version(dependency_name): "ExportIntentsMetadata", "ExportIntentsRequest", "ExportIntentsResponse", + "ExportPlaybookRequest", + "ExportPlaybookResponse", "ExportTestCasesMetadata", "ExportTestCasesRequest", "ExportTestCasesResponse", "FilterSpecs", "Flow", "FlowImportStrategy", + "FlowInvocation", + "FlowTransition", "FlowValidationResult", "FlowsClient", "Form", @@ -554,6 +652,7 @@ def _get_version(dependency_name): "GetDeploymentRequest", "GetEntityTypeRequest", "GetEnvironmentRequest", + "GetExampleRequest", "GetExperimentRequest", "GetFlowRequest", "GetFlowValidationResultRequest", @@ -561,13 +660,18 @@ def _get_version(dependency_name): "GetGeneratorRequest", "GetIntentRequest", "GetPageRequest", + "GetPlaybookRequest", + "GetPlaybookVersionRequest", "GetSecuritySettingsRequest", "GetSessionEntityTypeRequest", "GetTestCaseRequest", "GetTestCaseResultRequest", + "GetToolRequest", + "GetToolVersionRequest", "GetTransitionRouteGroupRequest", "GetVersionRequest", "GetWebhookRequest", + "Handler", "ImportEntityTypesMetadata", "ImportEntityTypesRequest", "ImportEntityTypesResponse", @@ -576,11 +680,14 @@ def _get_version(dependency_name): "ImportIntentsMetadata", "ImportIntentsRequest", "ImportIntentsResponse", + "ImportPlaybookRequest", + "ImportPlaybookResponse", "ImportStrategy", "ImportTestCasesMetadata", "ImportTestCasesRequest", "ImportTestCasesResponse", "InlineDestination", + "InlineSchema", "InlineSource", "InputAudioConfig", "Intent", @@ -602,6 +709,8 @@ def _get_version(dependency_name): "ListEntityTypesResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "ListExamplesRequest", + "ListExamplesResponse", "ListExperimentsRequest", "ListExperimentsResponse", "ListFlowsRequest", @@ -612,6 +721,10 @@ def _get_version(dependency_name): "ListIntentsResponse", "ListPagesRequest", "ListPagesResponse", + "ListPlaybookVersionsRequest", + "ListPlaybookVersionsResponse", + "ListPlaybooksRequest", + "ListPlaybooksResponse", "ListSecuritySettingsRequest", "ListSecuritySettingsResponse", "ListSessionEntityTypesRequest", @@ -620,12 +733,17 @@ def _get_version(dependency_name): "ListTestCaseResultsResponse", "ListTestCasesRequest", "ListTestCasesResponse", + "ListToolVersionsRequest", + "ListToolVersionsResponse", + "ListToolsRequest", + "ListToolsResponse", "ListTransitionRouteGroupsRequest", "ListTransitionRouteGroupsResponse", "ListVersionsRequest", "ListVersionsResponse", "ListWebhooksRequest", "ListWebhooksResponse", + "LlmModelSettings", "LoadVersionRequest", "LookupEnvironmentHistoryRequest", "LookupEnvironmentHistoryResponse", @@ -635,16 +753,30 @@ def _get_version(dependency_name): "NluSettings", "OutputAudioConfig", "OutputAudioEncoding", + "OutputState", "Page", "PageInfo", "PagesClient", + "ParameterDefinition", "Phrase", + "Playbook", + "PlaybookImportStrategy", + "PlaybookInput", + "PlaybookInvocation", + "PlaybookOutput", + "PlaybookTransition", + "PlaybookVersion", + "PlaybooksClient", "QueryInput", "QueryParameters", "QueryResult", "ResourceName", "ResponseMessage", "RestoreAgentRequest", + "RestorePlaybookVersionRequest", + "RestorePlaybookVersionResponse", + "RestoreToolVersionRequest", + "RestoreToolVersionResponse", "RolloutConfig", "RolloutState", "RunContinuousTestMetadata", @@ -683,27 +815,38 @@ def _get_version(dependency_name): "TestRunDifference", "TextInput", "TextToSpeechSettings", + "Tool", + "ToolCall", + "ToolCallResult", + "ToolUse", + "ToolVersion", + "ToolsClient", "TrainFlowRequest", "TransitionCoverage", "TransitionRoute", "TransitionRouteGroup", "TransitionRouteGroupCoverage", "TransitionRouteGroupsClient", + "TypeSchema", "UpdateAgentRequest", "UpdateEntityTypeRequest", "UpdateEnvironmentRequest", + "UpdateExampleRequest", "UpdateExperimentRequest", "UpdateFlowRequest", "UpdateGenerativeSettingsRequest", "UpdateGeneratorRequest", "UpdateIntentRequest", "UpdatePageRequest", + "UpdatePlaybookRequest", "UpdateSecuritySettingsRequest", "UpdateSessionEntityTypeRequest", "UpdateTestCaseRequest", + "UpdateToolRequest", "UpdateTransitionRouteGroupRequest", "UpdateVersionRequest", "UpdateWebhookRequest", + "UserUtterance", "ValidateAgentRequest", "ValidateFlowRequest", "ValidationMessage", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json index 5eaa14773707..b2fa7f125c5b 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -565,6 +565,100 @@ } } }, + "Examples": { + "clients": { + "grpc": { + "libraryClient": "ExamplesClient", + "rpcs": { + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExamplesAsyncClient", + "rpcs": { + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + } + } + }, + "rest": { + "libraryClient": "ExamplesClient", + "rpcs": { + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + } + } + } + } + }, "Experiments": { "clients": { "grpc": { @@ -1170,6 +1264,205 @@ } } }, + "Playbooks": { + "clients": { + "grpc": { + "libraryClient": "PlaybooksClient", + "rpcs": { + "CreatePlaybook": { + "methods": [ + "create_playbook" + ] + }, + "CreatePlaybookVersion": { + "methods": [ + "create_playbook_version" + ] + }, + "DeletePlaybook": { + "methods": [ + "delete_playbook" + ] + }, + "DeletePlaybookVersion": { + "methods": [ + "delete_playbook_version" + ] + }, + "ExportPlaybook": { + "methods": [ + "export_playbook" + ] + }, + "GetPlaybook": { + "methods": [ + "get_playbook" + ] + }, + "GetPlaybookVersion": { + "methods": [ + "get_playbook_version" + ] + }, + "ImportPlaybook": { + "methods": [ + "import_playbook" + ] + }, + "ListPlaybookVersions": { + "methods": [ + "list_playbook_versions" + ] + }, + "ListPlaybooks": { + "methods": [ + "list_playbooks" + ] + }, + "RestorePlaybookVersion": { + "methods": [ + "restore_playbook_version" + ] + }, + "UpdatePlaybook": { + "methods": [ + "update_playbook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PlaybooksAsyncClient", + "rpcs": { + "CreatePlaybook": { + "methods": [ + "create_playbook" + ] + }, + "CreatePlaybookVersion": { + "methods": [ + "create_playbook_version" + ] + }, + "DeletePlaybook": { + "methods": [ + "delete_playbook" + ] + }, + "DeletePlaybookVersion": { + "methods": [ + "delete_playbook_version" + ] + }, + "ExportPlaybook": { + "methods": [ + "export_playbook" + ] + }, + "GetPlaybook": { + "methods": [ + "get_playbook" + ] + }, + "GetPlaybookVersion": { + "methods": [ + "get_playbook_version" + ] + }, + "ImportPlaybook": { + "methods": [ + "import_playbook" + ] + }, + "ListPlaybookVersions": { + "methods": [ + "list_playbook_versions" + ] + }, + "ListPlaybooks": { + "methods": [ + "list_playbooks" + ] + }, + "RestorePlaybookVersion": { + "methods": [ + "restore_playbook_version" + ] + }, + "UpdatePlaybook": { + "methods": [ + "update_playbook" + ] + } + } + }, + "rest": { + "libraryClient": "PlaybooksClient", + "rpcs": { + "CreatePlaybook": { + "methods": [ + "create_playbook" + ] + }, + "CreatePlaybookVersion": { + "methods": [ + "create_playbook_version" + ] + }, + "DeletePlaybook": { + "methods": [ + "delete_playbook" + ] + }, + "DeletePlaybookVersion": { + "methods": [ + "delete_playbook_version" + ] + }, + "ExportPlaybook": { + "methods": [ + "export_playbook" + ] + }, + "GetPlaybook": { + "methods": [ + "get_playbook" + ] + }, + "GetPlaybookVersion": { + "methods": [ + "get_playbook_version" + ] + }, + "ImportPlaybook": { + "methods": [ + "import_playbook" + ] + }, + "ListPlaybookVersions": { + "methods": [ + "list_playbook_versions" + ] + }, + "ListPlaybooks": { + "methods": [ + "list_playbooks" + ] + }, + "RestorePlaybookVersion": { + "methods": [ + "restore_playbook_version" + ] + }, + "UpdatePlaybook": { + "methods": [ + "update_playbook" + ] + } + } + } + } + }, "SecuritySettingsService": { "clients": { "grpc": { @@ -1666,6 +1959,175 @@ } } }, + "Tools": { + "clients": { + "grpc": { + "libraryClient": "ToolsClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolVersion": { + "methods": [ + "create_tool_version" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolVersion": { + "methods": [ + "delete_tool_version" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolVersion": { + "methods": [ + "get_tool_version" + ] + }, + "ListToolVersions": { + "methods": [ + "list_tool_versions" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "RestoreToolVersion": { + "methods": [ + "restore_tool_version" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ToolsAsyncClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolVersion": { + "methods": [ + "create_tool_version" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolVersion": { + "methods": [ + "delete_tool_version" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolVersion": { + "methods": [ + "get_tool_version" + ] + }, + "ListToolVersions": { + "methods": [ + "list_tool_versions" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "RestoreToolVersion": { + "methods": [ + "restore_tool_version" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + }, + "rest": { + "libraryClient": "ToolsClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolVersion": { + "methods": [ + "create_tool_version" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolVersion": { + "methods": [ + "delete_tool_version" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolVersion": { + "methods": [ + "get_tool_version" + ] + }, + "ListToolVersions": { + "methods": [ + "list_tool_versions" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "RestoreToolVersion": { + "methods": [ + "restore_tool_version" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + } + } + }, "TransitionRouteGroups": { "clients": { "grpc": { diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py index 57cd59f2a8ff..acbb972957ad 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -111,6 +111,8 @@ class AgentsAsyncClient: parse_flow_validation_result_path = staticmethod( AgentsClient.parse_flow_validation_result_path ) + playbook_path = staticmethod(AgentsClient.playbook_path) + parse_playbook_path = staticmethod(AgentsClient.parse_playbook_path) secret_version_path = staticmethod(AgentsClient.secret_version_path) parse_secret_version_path = staticmethod(AgentsClient.parse_secret_version_path) security_settings_path = staticmethod(AgentsClient.security_settings_path) @@ -603,6 +605,7 @@ async def sample_create_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" @@ -745,6 +748,7 @@ async def sample_update_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py index 661780e8be8e..7ddf6965ae84 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -376,6 +376,30 @@ def parse_flow_validation_result_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def secret_version_path( project: str, @@ -1177,6 +1201,7 @@ def sample_create_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" @@ -1316,6 +1341,7 @@ def sample_update_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/async_client.py index b33e68f70631..ab61bbb4c9e1 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/async_client.py @@ -92,6 +92,10 @@ class EnvironmentsAsyncClient: ) environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + secret_version_path = staticmethod(EnvironmentsClient.secret_version_path) + parse_secret_version_path = staticmethod( + EnvironmentsClient.parse_secret_version_path + ) service_path = staticmethod(EnvironmentsClient.service_path) parse_service_path = staticmethod(EnvironmentsClient.parse_service_path) test_case_path = staticmethod(EnvironmentsClient.test_case_path) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/client.py index ab20238ce31f..a24810dcc2fe 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/environments/client.py @@ -283,6 +283,28 @@ def parse_environment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def secret_version_path( + project: str, + secret: str, + version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/__init__.py new file mode 100644 index 000000000000..20b0f9b21561 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import ExamplesAsyncClient +from .client import ExamplesClient + +__all__ = ( + "ExamplesClient", + "ExamplesAsyncClient", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/async_client.py new file mode 100644 index 000000000000..df457a0c524d --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/async_client.py @@ -0,0 +1,1188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.examples import pagers +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example +from google.cloud.dialogflowcx_v3.types import trace + +from .client import ExamplesClient +from .transports.base import DEFAULT_CLIENT_INFO, ExamplesTransport +from .transports.grpc_asyncio import ExamplesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class ExamplesAsyncClient: + """Service for managing + [Examples][google.cloud.dialogflow.cx.v3.Example]. + """ + + _client: ExamplesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ExamplesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExamplesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ExamplesClient._DEFAULT_UNIVERSE + + example_path = staticmethod(ExamplesClient.example_path) + parse_example_path = staticmethod(ExamplesClient.parse_example_path) + flow_path = staticmethod(ExamplesClient.flow_path) + parse_flow_path = staticmethod(ExamplesClient.parse_flow_path) + playbook_path = staticmethod(ExamplesClient.playbook_path) + parse_playbook_path = staticmethod(ExamplesClient.parse_playbook_path) + tool_path = staticmethod(ExamplesClient.tool_path) + parse_tool_path = staticmethod(ExamplesClient.parse_tool_path) + common_billing_account_path = staticmethod( + ExamplesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ExamplesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ExamplesClient.common_folder_path) + parse_common_folder_path = staticmethod(ExamplesClient.parse_common_folder_path) + common_organization_path = staticmethod(ExamplesClient.common_organization_path) + parse_common_organization_path = staticmethod( + ExamplesClient.parse_common_organization_path + ) + common_project_path = staticmethod(ExamplesClient.common_project_path) + parse_common_project_path = staticmethod(ExamplesClient.parse_common_project_path) + common_location_path = staticmethod(ExamplesClient.common_location_path) + parse_common_location_path = staticmethod(ExamplesClient.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: + ExamplesAsyncClient: The constructed client. + """ + return ExamplesClient.from_service_account_info.__func__(ExamplesAsyncClient, 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: + ExamplesAsyncClient: The constructed client. + """ + return ExamplesClient.from_service_account_file.__func__(ExamplesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ExamplesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ExamplesTransport: + """Returns the transport used by the client instance. + + Returns: + ExamplesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = ExamplesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ExamplesTransport, Callable[..., ExamplesTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the examples async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ExamplesTransport,Callable[..., ExamplesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ExamplesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ExamplesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.ExamplesAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "credentialsType": None, + }, + ) + + async def create_example( + self, + request: Optional[Union[gcdc_example.CreateExampleRequest, dict]] = None, + *, + parent: Optional[str] = None, + example: Optional[gcdc_example.Example] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Creates an example in the specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_create_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = await client.create_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.CreateExampleRequest, dict]]): + The request object. The request message for + [Examples.CreateExample][google.cloud.dialogflow.cx.v3.Examples.CreateExample]. + parent (:class:`str`): + Required. The playbook to create an example for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example (:class:`google.cloud.dialogflowcx_v3.types.Example`): + Required. The example to create. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, example] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_example.CreateExampleRequest): + request = gcdc_example.CreateExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if example is not None: + request.example = example + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_example( + self, + request: Optional[Union[example.DeleteExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_delete_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + await client.delete_example(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.DeleteExampleRequest, dict]]): + The request object. The request message for + [Examples.DeleteExample][google.cloud.dialogflow.cx.v3.Examples.DeleteExample]. + name (:class:`str`): + Required. The name of the example to delete. Format: + ``projects//locations//agents//playbooks//examples/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.DeleteExampleRequest): + request = example.DeleteExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_examples( + self, + request: Optional[Union[example.ListExamplesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExamplesAsyncPager: + r"""Returns a list of examples in the specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_list_examples(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ListExamplesRequest, dict]]): + The request object. The request message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + parent (:class:`str`): + Required. The playbook to list the examples from. + Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.examples.pagers.ListExamplesAsyncPager: + The response message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.ListExamplesRequest): + request = example.ListExamplesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_examples + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListExamplesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_example( + self, + request: Optional[Union[example.GetExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Retrieves the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_get_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetExampleRequest, dict]]): + The request object. The request message for + [Examples.GetExample][google.cloud.dialogflow.cx.v3.Examples.GetExample]. + name (:class:`str`): + Required. The name of the example. Format: + ``projects//locations//agents//playbooks//examples/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.GetExampleRequest): + request = example.GetExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_example( + self, + request: Optional[Union[gcdc_example.UpdateExampleRequest, dict]] = None, + *, + example: Optional[gcdc_example.Example] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Update the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_update_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = await client.update_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.UpdateExampleRequest, dict]]): + The request object. The request message for + [Examples.UpdateExample][google.cloud.dialogflow.cx.v3.Examples.UpdateExample]. + example (:class:`google.cloud.dialogflowcx_v3.types.Example`): + Required. The example to update. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The mask to control which + fields get updated. 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [example, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_example.UpdateExampleRequest): + request = gcdc_example.UpdateExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if example is not None: + request.example = example + 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._client._transport._wrapped_methods[ + self._client._transport.update_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("example.name", request.example.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ExamplesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("ExamplesAsyncClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/client.py new file mode 100644 index 000000000000..fdf166d4da9c --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/client.py @@ -0,0 +1,1709 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.examples import pagers +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example +from google.cloud.dialogflowcx_v3.types import trace + +from .transports.base import DEFAULT_CLIENT_INFO, ExamplesTransport +from .transports.grpc import ExamplesGrpcTransport +from .transports.grpc_asyncio import ExamplesGrpcAsyncIOTransport +from .transports.rest import ExamplesRestTransport + + +class ExamplesClientMeta(type): + """Metaclass for the Examples 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[ExamplesTransport]] + _transport_registry["grpc"] = ExamplesGrpcTransport + _transport_registry["grpc_asyncio"] = ExamplesGrpcAsyncIOTransport + _transport_registry["rest"] = ExamplesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ExamplesTransport]: + """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 ExamplesClient(metaclass=ExamplesClientMeta): + """Service for managing + [Examples][google.cloud.dialogflow.cx.v3.Example]. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ExamplesClient: 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: + ExamplesClient: 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) -> ExamplesTransport: + """Returns the transport used by the client instance. + + Returns: + ExamplesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def example_path( + project: str, + location: str, + agent: str, + playbook: str, + example: str, + ) -> str: + """Returns a fully-qualified example string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/examples/{example}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + example=example, + ) + + @staticmethod + def parse_example_path(path: str) -> Dict[str, str]: + """Parses a example path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)/examples/(?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 playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ExamplesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ExamplesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ExamplesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ExamplesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ExamplesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ExamplesTransport, Callable[..., ExamplesTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the examples client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ExamplesTransport,Callable[..., ExamplesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ExamplesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ExamplesClient._read_environment_variables() + self._client_cert_source = ExamplesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ExamplesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ExamplesTransport) + if transport_provided: + # transport is a ExamplesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ExamplesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ExamplesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ExamplesTransport], Callable[..., ExamplesTransport] + ] = ( + ExamplesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ExamplesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.ExamplesClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "credentialsType": None, + }, + ) + + def create_example( + self, + request: Optional[Union[gcdc_example.CreateExampleRequest, dict]] = None, + *, + parent: Optional[str] = None, + example: Optional[gcdc_example.Example] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Creates an example in the specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_create_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = client.create_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateExampleRequest, dict]): + The request object. The request message for + [Examples.CreateExample][google.cloud.dialogflow.cx.v3.Examples.CreateExample]. + parent (str): + Required. The playbook to create an example for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example (google.cloud.dialogflowcx_v3.types.Example): + Required. The example to create. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, example] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_example.CreateExampleRequest): + request = gcdc_example.CreateExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if example is not None: + request.example = example + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_example( + self, + request: Optional[Union[example.DeleteExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_delete_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + client.delete_example(request=request) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteExampleRequest, dict]): + The request object. The request message for + [Examples.DeleteExample][google.cloud.dialogflow.cx.v3.Examples.DeleteExample]. + name (str): + Required. The name of the example to delete. Format: + ``projects//locations//agents//playbooks//examples/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.DeleteExampleRequest): + request = example.DeleteExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_examples( + self, + request: Optional[Union[example.ListExamplesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExamplesPager: + r"""Returns a list of examples in the specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_list_examples(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListExamplesRequest, dict]): + The request object. The request message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + parent (str): + Required. The playbook to list the examples from. + Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.examples.pagers.ListExamplesPager: + The response message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.ListExamplesRequest): + request = example.ListExamplesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_examples] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListExamplesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_example( + self, + request: Optional[Union[example.GetExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Retrieves the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_get_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = client.get_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetExampleRequest, dict]): + The request object. The request message for + [Examples.GetExample][google.cloud.dialogflow.cx.v3.Examples.GetExample]. + name (str): + Required. The name of the example. Format: + ``projects//locations//agents//playbooks//examples/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, example.GetExampleRequest): + request = example.GetExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_example( + self, + request: Optional[Union[gcdc_example.UpdateExampleRequest, dict]] = None, + *, + example: Optional[gcdc_example.Example] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Update the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_update_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = client.update_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateExampleRequest, dict]): + The request object. The request message for + [Examples.UpdateExample][google.cloud.dialogflow.cx.v3.Examples.UpdateExample]. + example (google.cloud.dialogflowcx_v3.types.Example): + Required. The example to update. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which + fields get updated. 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [example, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_example.UpdateExampleRequest): + request = gcdc_example.UpdateExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if example is not None: + request.example = example + 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_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("example.name", request.example.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ExamplesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ExamplesClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/pagers.py new file mode 100644 index 000000000000..165405921244 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.dialogflowcx_v3.types import example + + +class ListExamplesPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExamplesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExamplesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., example.ListExamplesResponse], + request: example.ListExamplesRequest, + response: example.ListExamplesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExamplesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExamplesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = example.ListExamplesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[example.ListExamplesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[example.Example]: + for page in self.pages: + yield from page.examples + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExamplesAsyncPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExamplesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExamplesResponse` + attributes are available on the 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[example.ListExamplesResponse]], + request: example.ListExamplesRequest, + response: example.ListExamplesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExamplesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExamplesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = example.ListExamplesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[example.ListExamplesResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[example.Example]: + async def async_generator(): + async for page in self.pages: + for response in page.examples: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/README.rst b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/README.rst new file mode 100644 index 000000000000..0be06886f21c --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ExamplesTransport` is the ABC for all transports. +- public child `ExamplesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ExamplesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseExamplesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ExamplesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/__init__.py new file mode 100644 index 000000000000..5fa2ae88db98 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 ExamplesTransport +from .grpc import ExamplesGrpcTransport +from .grpc_asyncio import ExamplesGrpcAsyncIOTransport +from .rest import ExamplesRestInterceptor, ExamplesRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExamplesTransport]] +_transport_registry["grpc"] = ExamplesGrpcTransport +_transport_registry["grpc_asyncio"] = ExamplesGrpcAsyncIOTransport +_transport_registry["rest"] = ExamplesRestTransport + +__all__ = ( + "ExamplesTransport", + "ExamplesGrpcTransport", + "ExamplesGrpcAsyncIOTransport", + "ExamplesRestTransport", + "ExamplesRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/base.py new file mode 100644 index 000000000000..580d51616a14 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/base.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ExamplesTransport(abc.ABC): + """Abstract transport class for Examples.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_example: gapic_v1.method.wrap_method( + self.create_example, + default_timeout=None, + client_info=client_info, + ), + self.delete_example: gapic_v1.method.wrap_method( + self.delete_example, + default_timeout=None, + client_info=client_info, + ), + self.list_examples: gapic_v1.method.wrap_method( + self.list_examples, + default_timeout=None, + client_info=client_info, + ), + self.get_example: gapic_v1.method.wrap_method( + self.get_example, + default_timeout=None, + client_info=client_info, + ), + self.update_example: gapic_v1.method.wrap_method( + self.update_example, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_example( + self, + ) -> Callable[ + [gcdc_example.CreateExampleRequest], + Union[gcdc_example.Example, Awaitable[gcdc_example.Example]], + ]: + raise NotImplementedError() + + @property + def delete_example( + self, + ) -> Callable[ + [example.DeleteExampleRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_examples( + self, + ) -> Callable[ + [example.ListExamplesRequest], + Union[example.ListExamplesResponse, Awaitable[example.ListExamplesResponse]], + ]: + raise NotImplementedError() + + @property + def get_example( + self, + ) -> Callable[ + [example.GetExampleRequest], Union[example.Example, Awaitable[example.Example]] + ]: + raise NotImplementedError() + + @property + def update_example( + self, + ) -> Callable[ + [gcdc_example.UpdateExampleRequest], + Union[gcdc_example.Example, Awaitable[gcdc_example.Example]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ExamplesTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc.py new file mode 100644 index 000000000000..cd8e2188ac1e --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc.py @@ -0,0 +1,554 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example + +from .base import DEFAULT_CLIENT_INFO, ExamplesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ExamplesGrpcTransport(ExamplesTransport): + """gRPC backend transport for Examples. + + Service for managing + [Examples][google.cloud.dialogflow.cx.v3.Example]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_example( + self, + ) -> Callable[[gcdc_example.CreateExampleRequest], gcdc_example.Example]: + r"""Return a callable for the create example method over gRPC. + + Creates an example in the specified playbook. + + Returns: + Callable[[~.CreateExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example" not in self._stubs: + self._stubs["create_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/CreateExample", + request_serializer=gcdc_example.CreateExampleRequest.serialize, + response_deserializer=gcdc_example.Example.deserialize, + ) + return self._stubs["create_example"] + + @property + def delete_example( + self, + ) -> Callable[[example.DeleteExampleRequest], empty_pb2.Empty]: + r"""Return a callable for the delete example method over gRPC. + + Deletes the specified example. + + Returns: + Callable[[~.DeleteExampleRequest], + ~.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_example" not in self._stubs: + self._stubs["delete_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/DeleteExample", + request_serializer=example.DeleteExampleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_example"] + + @property + def list_examples( + self, + ) -> Callable[[example.ListExamplesRequest], example.ListExamplesResponse]: + r"""Return a callable for the list examples method over gRPC. + + Returns a list of examples in the specified playbook. + + Returns: + Callable[[~.ListExamplesRequest], + ~.ListExamplesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_examples" not in self._stubs: + self._stubs["list_examples"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/ListExamples", + request_serializer=example.ListExamplesRequest.serialize, + response_deserializer=example.ListExamplesResponse.deserialize, + ) + return self._stubs["list_examples"] + + @property + def get_example(self) -> Callable[[example.GetExampleRequest], example.Example]: + r"""Return a callable for the get example method over gRPC. + + Retrieves the specified example. + + Returns: + Callable[[~.GetExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_example" not in self._stubs: + self._stubs["get_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/GetExample", + request_serializer=example.GetExampleRequest.serialize, + response_deserializer=example.Example.deserialize, + ) + return self._stubs["get_example"] + + @property + def update_example( + self, + ) -> Callable[[gcdc_example.UpdateExampleRequest], gcdc_example.Example]: + r"""Return a callable for the update example method over gRPC. + + Update the specified example. + + Returns: + Callable[[~.UpdateExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example" not in self._stubs: + self._stubs["update_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/UpdateExample", + request_serializer=gcdc_example.UpdateExampleRequest.serialize, + response_deserializer=gcdc_example.Example.deserialize, + ) + return self._stubs["update_example"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ExamplesGrpcTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2ea3e92d6fd5 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/grpc_asyncio.py @@ -0,0 +1,626 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example + +from .base import DEFAULT_CLIENT_INFO, ExamplesTransport +from .grpc import ExamplesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ExamplesGrpcAsyncIOTransport(ExamplesTransport): + """gRPC AsyncIO backend transport for Examples. + + Service for managing + [Examples][google.cloud.dialogflow.cx.v3.Example]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_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_example( + self, + ) -> Callable[[gcdc_example.CreateExampleRequest], Awaitable[gcdc_example.Example]]: + r"""Return a callable for the create example method over gRPC. + + Creates an example in the specified playbook. + + Returns: + Callable[[~.CreateExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example" not in self._stubs: + self._stubs["create_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/CreateExample", + request_serializer=gcdc_example.CreateExampleRequest.serialize, + response_deserializer=gcdc_example.Example.deserialize, + ) + return self._stubs["create_example"] + + @property + def delete_example( + self, + ) -> Callable[[example.DeleteExampleRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete example method over gRPC. + + Deletes the specified example. + + Returns: + Callable[[~.DeleteExampleRequest], + 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_example" not in self._stubs: + self._stubs["delete_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/DeleteExample", + request_serializer=example.DeleteExampleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_example"] + + @property + def list_examples( + self, + ) -> Callable[ + [example.ListExamplesRequest], Awaitable[example.ListExamplesResponse] + ]: + r"""Return a callable for the list examples method over gRPC. + + Returns a list of examples in the specified playbook. + + Returns: + Callable[[~.ListExamplesRequest], + Awaitable[~.ListExamplesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_examples" not in self._stubs: + self._stubs["list_examples"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/ListExamples", + request_serializer=example.ListExamplesRequest.serialize, + response_deserializer=example.ListExamplesResponse.deserialize, + ) + return self._stubs["list_examples"] + + @property + def get_example( + self, + ) -> Callable[[example.GetExampleRequest], Awaitable[example.Example]]: + r"""Return a callable for the get example method over gRPC. + + Retrieves the specified example. + + Returns: + Callable[[~.GetExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_example" not in self._stubs: + self._stubs["get_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/GetExample", + request_serializer=example.GetExampleRequest.serialize, + response_deserializer=example.Example.deserialize, + ) + return self._stubs["get_example"] + + @property + def update_example( + self, + ) -> Callable[[gcdc_example.UpdateExampleRequest], Awaitable[gcdc_example.Example]]: + r"""Return a callable for the update example method over gRPC. + + Update the specified example. + + Returns: + Callable[[~.UpdateExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_example" not in self._stubs: + self._stubs["update_example"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Examples/UpdateExample", + request_serializer=gcdc_example.UpdateExampleRequest.serialize, + response_deserializer=gcdc_example.Example.deserialize, + ) + return self._stubs["update_example"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_example: self._wrap_method( + self.create_example, + default_timeout=None, + client_info=client_info, + ), + self.delete_example: self._wrap_method( + self.delete_example, + default_timeout=None, + client_info=client_info, + ), + self.list_examples: self._wrap_method( + self.list_examples, + default_timeout=None, + client_info=client_info, + ), + self.get_example: self._wrap_method( + self.get_example, + default_timeout=None, + client_info=client_info, + ), + self.update_example: self._wrap_method( + self.update_example, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("ExamplesGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest.py new file mode 100644 index 000000000000..a28ff38c862a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest.py @@ -0,0 +1,2002 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseExamplesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ExamplesRestInterceptor: + """Interceptor for Examples. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ExamplesRestTransport. + + .. code-block:: python + class MyCustomExamplesInterceptor(ExamplesRestInterceptor): + def pre_create_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_example(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_example(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_examples(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_examples(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_example(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ExamplesRestTransport(interceptor=MyCustomExamplesInterceptor()) + client = ExamplesClient(transport=transport) + + + """ + + def pre_create_example( + self, + request: gcdc_example.CreateExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcdc_example.CreateExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_create_example( + self, response: gcdc_example.Example + ) -> gcdc_example.Example: + """Post-rpc interceptor for create_example + + DEPRECATED. Please use the `post_create_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Examples server but before + it is returned to user code. This `post_create_example` interceptor runs + before the `post_create_example_with_metadata` interceptor. + """ + return response + + def post_create_example_with_metadata( + self, + response: gcdc_example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Examples server but before it is returned to user code. + + We recommend only using this `post_create_example_with_metadata` + interceptor in new development instead of the `post_create_example` interceptor. + When both interceptors are used, this `post_create_example_with_metadata` interceptor runs after the + `post_create_example` interceptor. The (possibly modified) response returned by + `post_create_example` will be passed to + `post_create_example_with_metadata`. + """ + return response, metadata + + def pre_delete_example( + self, + request: example.DeleteExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.DeleteExampleRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def pre_get_example( + self, + request: example.GetExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.GetExampleRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_get_example(self, response: example.Example) -> example.Example: + """Post-rpc interceptor for get_example + + DEPRECATED. Please use the `post_get_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Examples server but before + it is returned to user code. This `post_get_example` interceptor runs + before the `post_get_example_with_metadata` interceptor. + """ + return response + + def post_get_example_with_metadata( + self, + response: example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Examples server but before it is returned to user code. + + We recommend only using this `post_get_example_with_metadata` + interceptor in new development instead of the `post_get_example` interceptor. + When both interceptors are used, this `post_get_example_with_metadata` interceptor runs after the + `post_get_example` interceptor. The (possibly modified) response returned by + `post_get_example` will be passed to + `post_get_example_with_metadata`. + """ + return response, metadata + + def pre_list_examples( + self, + request: example.ListExamplesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.ListExamplesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_examples + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_list_examples( + self, response: example.ListExamplesResponse + ) -> example.ListExamplesResponse: + """Post-rpc interceptor for list_examples + + DEPRECATED. Please use the `post_list_examples_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Examples server but before + it is returned to user code. This `post_list_examples` interceptor runs + before the `post_list_examples_with_metadata` interceptor. + """ + return response + + def post_list_examples_with_metadata( + self, + response: example.ListExamplesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.ListExamplesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_examples + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Examples server but before it is returned to user code. + + We recommend only using this `post_list_examples_with_metadata` + interceptor in new development instead of the `post_list_examples` interceptor. + When both interceptors are used, this `post_list_examples_with_metadata` interceptor runs after the + `post_list_examples` interceptor. The (possibly modified) response returned by + `post_list_examples` will be passed to + `post_list_examples_with_metadata`. + """ + return response, metadata + + def pre_update_example( + self, + request: gcdc_example.UpdateExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcdc_example.UpdateExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_update_example( + self, response: gcdc_example.Example + ) -> gcdc_example.Example: + """Post-rpc interceptor for update_example + + DEPRECATED. Please use the `post_update_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Examples server but before + it is returned to user code. This `post_update_example` interceptor runs + before the `post_update_example_with_metadata` interceptor. + """ + return response + + def post_update_example_with_metadata( + self, + response: gcdc_example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Examples server but before it is returned to user code. + + We recommend only using this `post_update_example_with_metadata` + interceptor in new development instead of the `post_update_example` interceptor. + When both interceptors are used, this `post_update_example_with_metadata` interceptor runs after the + `post_update_example` interceptor. The (possibly modified) response returned by + `post_update_example` will be passed to + `post_update_example_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Examples server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Examples server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Examples server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Examples server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Examples server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Examples server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ExamplesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ExamplesRestInterceptor + + +class ExamplesRestTransport(_BaseExamplesRestTransport): + """REST backend synchronous transport for Examples. + + Service for managing + [Examples][google.cloud.dialogflow.cx.v3.Example]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ExamplesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ExamplesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateExample( + _BaseExamplesRestTransport._BaseCreateExample, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.CreateExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_example.CreateExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Call the create example method over HTTP. + + Args: + request (~.gcdc_example.CreateExampleRequest): + The request object. The request message for + [Examples.CreateExample][google.cloud.dialogflow.cx.v3.Examples.CreateExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_example.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + + http_options = ( + _BaseExamplesRestTransport._BaseCreateExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_example(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseCreateExample._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseExamplesRestTransport._BaseCreateExample._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseCreateExample._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.CreateExample", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "CreateExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._CreateExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_example.Example() + pb_resp = gcdc_example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesClient.create_example", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "CreateExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteExample( + _BaseExamplesRestTransport._BaseDeleteExample, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.DeleteExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: example.DeleteExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete example method over HTTP. + + Args: + request (~.example.DeleteExampleRequest): + The request object. The request message for + [Examples.DeleteExample][google.cloud.dialogflow.cx.v3.Examples.DeleteExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseDeleteExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_example(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseDeleteExample._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseDeleteExample._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.DeleteExample", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "DeleteExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._DeleteExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetExample(_BaseExamplesRestTransport._BaseGetExample, ExamplesRestStub): + def __hash__(self): + return hash("ExamplesRestTransport.GetExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: example.GetExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Call the get example method over HTTP. + + Args: + request (~.example.GetExampleRequest): + The request object. The request message for + [Examples.GetExample][google.cloud.dialogflow.cx.v3.Examples.GetExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.example.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + + http_options = ( + _BaseExamplesRestTransport._BaseGetExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_example(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseGetExample._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseGetExample._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.GetExample", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._GetExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = example.Example() + pb_resp = example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesClient.get_example", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListExamples(_BaseExamplesRestTransport._BaseListExamples, ExamplesRestStub): + def __hash__(self): + return hash("ExamplesRestTransport.ListExamples") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: example.ListExamplesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.ListExamplesResponse: + r"""Call the list examples method over HTTP. + + Args: + request (~.example.ListExamplesRequest): + The request object. The request message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.example.ListExamplesResponse: + The response message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + + """ + + http_options = ( + _BaseExamplesRestTransport._BaseListExamples._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_examples(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseListExamples._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseListExamples._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.ListExamples", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListExamples", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._ListExamples._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = example.ListExamplesResponse() + pb_resp = example.ListExamplesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_examples(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_examples_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = example.ListExamplesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesClient.list_examples", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListExamples", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateExample( + _BaseExamplesRestTransport._BaseUpdateExample, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.UpdateExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_example.UpdateExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_example.Example: + r"""Call the update example method over HTTP. + + Args: + request (~.gcdc_example.UpdateExampleRequest): + The request object. The request message for + [Examples.UpdateExample][google.cloud.dialogflow.cx.v3.Examples.UpdateExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_example.Example: + Example represents a sample execution + of the playbook in the conversation. + An example consists of a list of ordered + actions performed by end user or + Dialogflow agent according the playbook + instructions to fulfill the task. + + """ + + http_options = ( + _BaseExamplesRestTransport._BaseUpdateExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_example(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseUpdateExample._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseExamplesRestTransport._BaseUpdateExample._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseUpdateExample._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.UpdateExample", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "UpdateExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._UpdateExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_example.Example() + pb_resp = gcdc_example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesClient.update_example", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "UpdateExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_example( + self, + ) -> Callable[[gcdc_example.CreateExampleRequest], gcdc_example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_example( + self, + ) -> Callable[[example.DeleteExampleRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_example(self) -> Callable[[example.GetExampleRequest], example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_examples( + self, + ) -> Callable[[example.ListExamplesRequest], example.ListExamplesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListExamples(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_example( + self, + ) -> Callable[[gcdc_example.UpdateExampleRequest], gcdc_example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseExamplesRestTransport._BaseGetLocation, ExamplesRestStub): + def __hash__(self): + return hash("ExamplesRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseExamplesRestTransport._BaseListLocations, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseExamplesRestTransport._BaseCancelOperation, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = ( + _BaseExamplesRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseExamplesRestTransport._BaseGetOperation, ExamplesRestStub): + def __hash__(self): + return hash("ExamplesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseExamplesRestTransport._BaseListOperations, ExamplesRestStub + ): + def __hash__(self): + return hash("ExamplesRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseExamplesRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseExamplesRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseExamplesRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ExamplesClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ExamplesRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ExamplesAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Examples", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ExamplesRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest_base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest_base.py new file mode 100644 index 000000000000..8dc5f698eafe --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/examples/transports/rest_base.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example + +from .base import DEFAULT_CLIENT_INFO, ExamplesTransport + + +class _BaseExamplesRestTransport(ExamplesTransport): + """Base REST backend transport for Examples. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples", + "body": "example", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_example.CreateExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExamplesRestTransport._BaseCreateExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = example.DeleteExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExamplesRestTransport._BaseDeleteExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = example.GetExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExamplesRestTransport._BaseGetExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListExamples: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = example.ListExamplesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExamplesRestTransport._BaseListExamples._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{example.name=projects/*/locations/*/agents/*/playbooks/*/examples/*}", + "body": "example", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_example.UpdateExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExamplesRestTransport._BaseUpdateExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseExamplesRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/async_client.py index 7319e0790eab..39f74ee86344 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/async_client.py @@ -54,10 +54,14 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import ( + page, + parameter_definition, + validation_message, +) from google.cloud.dialogflowcx_v3.types import advanced_settings 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, validation_message from .client import FlowsClient from .transports.base import DEFAULT_CLIENT_INFO, FlowsTransport @@ -97,6 +101,10 @@ class FlowsAsyncClient: parse_intent_path = staticmethod(FlowsClient.parse_intent_path) page_path = staticmethod(FlowsClient.page_path) parse_page_path = staticmethod(FlowsClient.parse_page_path) + playbook_path = staticmethod(FlowsClient.playbook_path) + parse_playbook_path = staticmethod(FlowsClient.parse_playbook_path) + tool_path = staticmethod(FlowsClient.tool_path) + parse_tool_path = staticmethod(FlowsClient.parse_tool_path) transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) parse_transition_route_group_path = staticmethod( FlowsClient.parse_transition_route_group_path diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/client.py index dcba8bc2f30a..5b986336d53f 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/flows/client.py @@ -71,10 +71,14 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import ( + page, + parameter_definition, + validation_message, +) from google.cloud.dialogflowcx_v3.types import advanced_settings 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, validation_message from .transports.base import DEFAULT_CLIENT_INFO, FlowsTransport from .transports.grpc import FlowsGrpcTransport @@ -356,6 +360,54 @@ def parse_page_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def transition_route_group_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/async_client.py index 6ce38938fe25..646a15dad716 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/async_client.py @@ -49,6 +49,7 @@ from google.protobuf import field_mask_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.generators import pagers +from google.cloud.dialogflowcx_v3.types import generative_settings from google.cloud.dialogflowcx_v3.types import generator from google.cloud.dialogflowcx_v3.types import generator as gcdc_generator diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/client.py index e76ff3c15c3f..44e5a8e01c2c 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/generators/client.py @@ -66,6 +66,7 @@ from google.protobuf import field_mask_pb2 # type: ignore from google.cloud.dialogflowcx_v3.services.generators import pagers +from google.cloud.dialogflowcx_v3.types import generative_settings from google.cloud.dialogflowcx_v3.types import generator from google.cloud.dialogflowcx_v3.types import generator as gcdc_generator diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/async_client.py index 281855f9f8e2..ba174c5044f4 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/async_client.py @@ -89,6 +89,10 @@ class PagesAsyncClient: parse_intent_path = staticmethod(PagesClient.parse_intent_path) page_path = staticmethod(PagesClient.page_path) parse_page_path = staticmethod(PagesClient.parse_page_path) + playbook_path = staticmethod(PagesClient.playbook_path) + parse_playbook_path = staticmethod(PagesClient.parse_playbook_path) + tool_path = staticmethod(PagesClient.tool_path) + parse_tool_path = staticmethod(PagesClient.parse_tool_path) transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) parse_transition_route_group_path = staticmethod( PagesClient.parse_transition_route_group_path diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/client.py index 7d9388ab7057..a46889044876 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/pages/client.py @@ -350,6 +350,54 @@ def parse_page_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def transition_route_group_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/__init__.py new file mode 100644 index 000000000000..006d2462f5dc --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PlaybooksAsyncClient +from .client import PlaybooksClient + +__all__ = ( + "PlaybooksClient", + "PlaybooksAsyncClient", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/async_client.py new file mode 100644 index 000000000000..b2fce9622ec7 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/async_client.py @@ -0,0 +1,2000 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_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.cloud.dialogflowcx_v3.services.playbooks import pagers +from google.cloud.dialogflowcx_v3.types import ( + code_block, + example, + generative_settings, + parameter_definition, +) +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .client import PlaybooksClient +from .transports.base import DEFAULT_CLIENT_INFO, PlaybooksTransport +from .transports.grpc_asyncio import PlaybooksGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PlaybooksAsyncClient: + """Service for managing + [Playbooks][google.cloud.dialogflow.cx.v3.Playbook]. + """ + + _client: PlaybooksClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PlaybooksClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PlaybooksClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PlaybooksClient._DEFAULT_UNIVERSE + + example_path = staticmethod(PlaybooksClient.example_path) + parse_example_path = staticmethod(PlaybooksClient.parse_example_path) + flow_path = staticmethod(PlaybooksClient.flow_path) + parse_flow_path = staticmethod(PlaybooksClient.parse_flow_path) + generator_path = staticmethod(PlaybooksClient.generator_path) + parse_generator_path = staticmethod(PlaybooksClient.parse_generator_path) + playbook_path = staticmethod(PlaybooksClient.playbook_path) + parse_playbook_path = staticmethod(PlaybooksClient.parse_playbook_path) + playbook_version_path = staticmethod(PlaybooksClient.playbook_version_path) + parse_playbook_version_path = staticmethod( + PlaybooksClient.parse_playbook_version_path + ) + tool_path = staticmethod(PlaybooksClient.tool_path) + parse_tool_path = staticmethod(PlaybooksClient.parse_tool_path) + webhook_path = staticmethod(PlaybooksClient.webhook_path) + parse_webhook_path = staticmethod(PlaybooksClient.parse_webhook_path) + common_billing_account_path = staticmethod( + PlaybooksClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PlaybooksClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PlaybooksClient.common_folder_path) + parse_common_folder_path = staticmethod(PlaybooksClient.parse_common_folder_path) + common_organization_path = staticmethod(PlaybooksClient.common_organization_path) + parse_common_organization_path = staticmethod( + PlaybooksClient.parse_common_organization_path + ) + common_project_path = staticmethod(PlaybooksClient.common_project_path) + parse_common_project_path = staticmethod(PlaybooksClient.parse_common_project_path) + common_location_path = staticmethod(PlaybooksClient.common_location_path) + parse_common_location_path = staticmethod( + PlaybooksClient.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: + PlaybooksAsyncClient: The constructed client. + """ + return PlaybooksClient.from_service_account_info.__func__(PlaybooksAsyncClient, 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: + PlaybooksAsyncClient: The constructed client. + """ + return PlaybooksClient.from_service_account_file.__func__(PlaybooksAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PlaybooksClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PlaybooksTransport: + """Returns the transport used by the client instance. + + Returns: + PlaybooksTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PlaybooksClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PlaybooksTransport, Callable[..., PlaybooksTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the playbooks async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PlaybooksTransport,Callable[..., PlaybooksTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PlaybooksTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PlaybooksClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.PlaybooksAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "credentialsType": None, + }, + ) + + async def create_playbook( + self, + request: Optional[Union[gcdc_playbook.CreatePlaybookRequest, dict]] = None, + *, + parent: Optional[str] = None, + playbook: Optional[gcdc_playbook.Playbook] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Creates a playbook in a specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_create_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.CreatePlaybookRequest( + parent="parent_value", + playbook=playbook, + ) + + # Make the request + response = await client.create_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.CreatePlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.CreatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook]. + parent (:class:`str`): + Required. The agent to create a playbook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + playbook (:class:`google.cloud.dialogflowcx_v3.types.Playbook`): + Required. The playbook to create. + This corresponds to the ``playbook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, playbook] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_playbook.CreatePlaybookRequest): + request = gcdc_playbook.CreatePlaybookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if playbook is not None: + request.playbook = playbook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_playbook( + self, + request: Optional[Union[playbook.DeletePlaybookRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_delete_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookRequest( + name="name_value", + ) + + # Make the request + await client.delete_playbook(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.DeletePlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.DeletePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook]. + name (:class:`str`): + Required. The name of the playbook to delete. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.DeletePlaybookRequest): + request = playbook.DeletePlaybookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_playbooks( + self, + request: Optional[Union[playbook.ListPlaybooksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPlaybooksAsyncPager: + r"""Returns a list of playbooks in the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_list_playbooks(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybooksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbooks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest, dict]]): + The request object. The request message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + parent (:class:`str`): + Required. The agent to list playbooks 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybooksAsyncPager: + The response message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ListPlaybooksRequest): + request = playbook.ListPlaybooksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_playbooks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListPlaybooksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_playbook( + self, + request: Optional[Union[playbook.GetPlaybookRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.Playbook: + r"""Retrieves the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_get_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookRequest( + name="name_value", + ) + + # Make the request + response = await client.get_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetPlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.GetPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook]. + name (:class:`str`): + Required. The name of the playbook. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.GetPlaybookRequest): + request = playbook.GetPlaybookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def export_playbook( + self, + request: Optional[Union[playbook.ExportPlaybookRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified playbook to a binary file. + + Note that resources (e.g. examples, tools) that the + playbook references will also be exported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_export_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ExportPlaybookRequest( + name="name_value", + ) + + # Make the request + operation = client.export_playbook(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ExportPlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.ExportPlaybookResponse` The response message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ExportPlaybookRequest): + request = playbook.ExportPlaybookRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + playbook.ExportPlaybookResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def import_playbook( + self, + request: Optional[Union[playbook.ImportPlaybookRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified playbook to the specified agent + from a binary file. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_import_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ImportPlaybookRequest( + playbook_uri="playbook_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_playbook(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ImportPlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.ImportPlaybookResponse` The response message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ImportPlaybookRequest): + request = playbook.ImportPlaybookRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + playbook.ImportPlaybookResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def update_playbook( + self, + request: Optional[Union[gcdc_playbook.UpdatePlaybookRequest, dict]] = None, + *, + playbook: Optional[gcdc_playbook.Playbook] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Updates the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_update_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.UpdatePlaybookRequest( + playbook=playbook, + ) + + # Make the request + response = await client.update_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.UpdatePlaybookRequest, dict]]): + The request object. The request message for + [Playbooks.UpdatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook]. + playbook (:class:`google.cloud.dialogflowcx_v3.types.Playbook`): + Required. The playbook to update. + This corresponds to the ``playbook`` 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [playbook, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_playbook.UpdatePlaybookRequest): + request = gcdc_playbook.UpdatePlaybookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if playbook is not None: + request.playbook = playbook + 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._client._transport._wrapped_methods[ + self._client._transport.update_playbook + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("playbook.name", request.playbook.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_playbook_version( + self, + request: Optional[Union[playbook.CreatePlaybookVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + playbook_version: Optional[playbook.PlaybookVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Creates a version for the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_create_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.CreatePlaybookVersionRequest, dict]]): + The request object. The request message for + [Playbooks.CreatePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion]. + parent (:class:`str`): + Required. The playbook to create a version for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + playbook_version (:class:`google.cloud.dialogflowcx_v3.types.PlaybookVersion`): + Required. The playbook version to + create. + + This corresponds to the ``playbook_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, playbook_version] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.CreatePlaybookVersionRequest): + request = playbook.CreatePlaybookVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if playbook_version is not None: + request.playbook_version = playbook_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_playbook_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_playbook_version( + self, + request: Optional[Union[playbook.GetPlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Retrieves the specified version of the Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_get_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetPlaybookVersionRequest, dict]]): + The request object. The request message for + [Playbooks.GetPlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion]. + name (:class:`str`): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.GetPlaybookVersionRequest): + request = playbook.GetPlaybookVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_playbook_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def restore_playbook_version( + self, + request: Optional[Union[playbook.RestorePlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.RestorePlaybookVersionResponse: + r"""Retrieves the specified version of the Playbook and + stores it as the current playbook draft, returning the + playbook with resources updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_restore_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestorePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionRequest, dict]]): + The request object. The request message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + name (:class:`str`): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionResponse: + The response message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.RestorePlaybookVersionRequest): + request = playbook.RestorePlaybookVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.restore_playbook_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_playbook_versions( + self, + request: Optional[Union[playbook.ListPlaybookVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPlaybookVersionsAsyncPager: + r"""Lists versions for the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_list_playbook_versions(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybookVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbook_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest, dict]]): + The request object. The request message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + parent (:class:`str`): + Required. The playbook to list versions for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybookVersionsAsyncPager: + The response message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ListPlaybookVersionsRequest): + request = playbook.ListPlaybookVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_playbook_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListPlaybookVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_playbook_version( + self, + request: Optional[Union[playbook.DeletePlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified version of the Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_delete_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_playbook_version(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.DeletePlaybookVersionRequest, dict]]): + The request object. The request message for + [Playbooks.DeletePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion]. + name (:class:`str`): + Required. The name of the playbook version to delete. + Format: + ``projects//locations//agents//playbooks//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.DeletePlaybookVersionRequest): + request = playbook.DeletePlaybookVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_playbook_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PlaybooksAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PlaybooksAsyncClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/client.py new file mode 100644 index 000000000000..4c38bc3d6b30 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/client.py @@ -0,0 +1,2566 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_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.cloud.dialogflowcx_v3.services.playbooks import pagers +from google.cloud.dialogflowcx_v3.types import ( + code_block, + example, + generative_settings, + parameter_definition, +) +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .transports.base import DEFAULT_CLIENT_INFO, PlaybooksTransport +from .transports.grpc import PlaybooksGrpcTransport +from .transports.grpc_asyncio import PlaybooksGrpcAsyncIOTransport +from .transports.rest import PlaybooksRestTransport + + +class PlaybooksClientMeta(type): + """Metaclass for the Playbooks 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[PlaybooksTransport]] + _transport_registry["grpc"] = PlaybooksGrpcTransport + _transport_registry["grpc_asyncio"] = PlaybooksGrpcAsyncIOTransport + _transport_registry["rest"] = PlaybooksRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PlaybooksTransport]: + """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 PlaybooksClient(metaclass=PlaybooksClientMeta): + """Service for managing + [Playbooks][google.cloud.dialogflow.cx.v3.Playbook]. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PlaybooksClient: 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: + PlaybooksClient: 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) -> PlaybooksTransport: + """Returns the transport used by the client instance. + + Returns: + PlaybooksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def example_path( + project: str, + location: str, + agent: str, + playbook: str, + example: str, + ) -> str: + """Returns a fully-qualified example string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/examples/{example}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + example=example, + ) + + @staticmethod + def parse_example_path(path: str) -> Dict[str, str]: + """Parses a example path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)/examples/(?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 generator_path( + project: str, + location: str, + agent: str, + generator: str, + ) -> str: + """Returns a fully-qualified generator string.""" + return "projects/{project}/locations/{location}/agents/{agent}/generators/{generator}".format( + project=project, + location=location, + agent=agent, + generator=generator, + ) + + @staticmethod + def parse_generator_path(path: str) -> Dict[str, str]: + """Parses a generator path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/generators/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def playbook_version_path( + project: str, + location: str, + agent: str, + playbook: str, + version: str, + ) -> str: + """Returns a fully-qualified playbook_version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/versions/{version}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + version=version, + ) + + @staticmethod + def parse_playbook_version_path(path: str) -> Dict[str, str]: + """Parses a playbook_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PlaybooksClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PlaybooksClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PlaybooksClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PlaybooksClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PlaybooksClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PlaybooksTransport, Callable[..., PlaybooksTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the playbooks client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PlaybooksTransport,Callable[..., PlaybooksTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PlaybooksTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = PlaybooksClient._read_environment_variables() + self._client_cert_source = PlaybooksClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PlaybooksClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PlaybooksTransport) + if transport_provided: + # transport is a PlaybooksTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(PlaybooksTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or PlaybooksClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PlaybooksTransport], Callable[..., PlaybooksTransport] + ] = ( + PlaybooksClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PlaybooksTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.PlaybooksClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "credentialsType": None, + }, + ) + + def create_playbook( + self, + request: Optional[Union[gcdc_playbook.CreatePlaybookRequest, dict]] = None, + *, + parent: Optional[str] = None, + playbook: Optional[gcdc_playbook.Playbook] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Creates a playbook in a specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_create_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.CreatePlaybookRequest( + parent="parent_value", + playbook=playbook, + ) + + # Make the request + response = client.create_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreatePlaybookRequest, dict]): + The request object. The request message for + [Playbooks.CreatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook]. + parent (str): + Required. The agent to create a playbook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + Required. The playbook to create. + This corresponds to the ``playbook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, playbook] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_playbook.CreatePlaybookRequest): + request = gcdc_playbook.CreatePlaybookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if playbook is not None: + request.playbook = playbook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_playbook( + self, + request: Optional[Union[playbook.DeletePlaybookRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a specified playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_delete_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookRequest( + name="name_value", + ) + + # Make the request + client.delete_playbook(request=request) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeletePlaybookRequest, dict]): + The request object. The request message for + [Playbooks.DeletePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook]. + name (str): + Required. The name of the playbook to delete. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.DeletePlaybookRequest): + request = playbook.DeletePlaybookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_playbooks( + self, + request: Optional[Union[playbook.ListPlaybooksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPlaybooksPager: + r"""Returns a list of playbooks in the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_list_playbooks(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybooksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbooks(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest, dict]): + The request object. The request message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + parent (str): + Required. The agent to list playbooks 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybooksPager: + The response message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ListPlaybooksRequest): + request = playbook.ListPlaybooksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbooks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListPlaybooksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_playbook( + self, + request: Optional[Union[playbook.GetPlaybookRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.Playbook: + r"""Retrieves the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_get_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookRequest( + name="name_value", + ) + + # Make the request + response = client.get_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetPlaybookRequest, dict]): + The request object. The request message for + [Playbooks.GetPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook]. + name (str): + Required. The name of the playbook. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.GetPlaybookRequest): + request = playbook.GetPlaybookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def export_playbook( + self, + request: Optional[Union[playbook.ExportPlaybookRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Exports the specified playbook to a binary file. + + Note that resources (e.g. examples, tools) that the + playbook references will also be exported. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_export_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ExportPlaybookRequest( + name="name_value", + ) + + # Make the request + operation = client.export_playbook(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ExportPlaybookRequest, dict]): + The request object. The request message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.ExportPlaybookResponse` The response message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ExportPlaybookRequest): + request = playbook.ExportPlaybookRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + playbook.ExportPlaybookResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def import_playbook( + self, + request: Optional[Union[playbook.ImportPlaybookRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Imports the specified playbook to the specified agent + from a binary file. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_import_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ImportPlaybookRequest( + playbook_uri="playbook_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_playbook(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ImportPlaybookRequest, dict]): + The request object. The request message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.ImportPlaybookResponse` The response message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ImportPlaybookRequest): + request = playbook.ImportPlaybookRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + playbook.ImportPlaybookResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def update_playbook( + self, + request: Optional[Union[gcdc_playbook.UpdatePlaybookRequest, dict]] = None, + *, + playbook: Optional[gcdc_playbook.Playbook] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Updates the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_update_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.UpdatePlaybookRequest( + playbook=playbook, + ) + + # Make the request + response = client.update_playbook(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdatePlaybookRequest, dict]): + The request object. The request message for + [Playbooks.UpdatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook]. + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + Required. The playbook to update. + This corresponds to the ``playbook`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [playbook, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_playbook.UpdatePlaybookRequest): + request = gcdc_playbook.UpdatePlaybookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if playbook is not None: + request.playbook = playbook + 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_playbook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("playbook.name", request.playbook.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_playbook_version( + self, + request: Optional[Union[playbook.CreatePlaybookVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + playbook_version: Optional[playbook.PlaybookVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Creates a version for the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_create_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreatePlaybookVersionRequest, dict]): + The request object. The request message for + [Playbooks.CreatePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion]. + parent (str): + Required. The playbook to create a version for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + playbook_version (google.cloud.dialogflowcx_v3.types.PlaybookVersion): + Required. The playbook version to + create. + + This corresponds to the ``playbook_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, playbook_version] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.CreatePlaybookVersionRequest): + request = playbook.CreatePlaybookVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if playbook_version is not None: + request.playbook_version = playbook_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_playbook_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_playbook_version( + self, + request: Optional[Union[playbook.GetPlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Retrieves the specified version of the Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_get_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetPlaybookVersionRequest, dict]): + The request object. The request message for + [Playbooks.GetPlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion]. + name (str): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.GetPlaybookVersionRequest): + request = playbook.GetPlaybookVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbook_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def restore_playbook_version( + self, + request: Optional[Union[playbook.RestorePlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.RestorePlaybookVersionResponse: + r"""Retrieves the specified version of the Playbook and + stores it as the current playbook draft, returning the + playbook with resources updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_restore_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestorePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_playbook_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionRequest, dict]): + The request object. The request message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + name (str): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionResponse: + The response message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.RestorePlaybookVersionRequest): + request = playbook.RestorePlaybookVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.restore_playbook_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_playbook_versions( + self, + request: Optional[Union[playbook.ListPlaybookVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPlaybookVersionsPager: + r"""Lists versions for the specified Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_list_playbook_versions(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybookVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbook_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest, dict]): + The request object. The request message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + parent (str): + Required. The playbook to list versions for. Format: + ``projects//locations//agents//playbooks/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybookVersionsPager: + The response message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.ListPlaybookVersionsRequest): + request = playbook.ListPlaybookVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbook_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListPlaybookVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_playbook_version( + self, + request: Optional[Union[playbook.DeletePlaybookVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified version of the Playbook. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_delete_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_playbook_version(request=request) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeletePlaybookVersionRequest, dict]): + The request object. The request message for + [Playbooks.DeletePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion]. + name (str): + Required. The name of the playbook version to delete. + Format: + ``projects//locations//agents//playbooks//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, playbook.DeletePlaybookVersionRequest): + request = playbook.DeletePlaybookVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_playbook_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "PlaybooksClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PlaybooksClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/pagers.py new file mode 100644 index 000000000000..992ec0b013c7 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/pagers.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.dialogflowcx_v3.types import playbook + + +class ListPlaybooksPager: + """A pager for iterating through ``list_playbooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``playbooks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPlaybooks`` requests and continue to iterate + through the ``playbooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., playbook.ListPlaybooksResponse], + request: playbook.ListPlaybooksRequest, + response: playbook.ListPlaybooksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = playbook.ListPlaybooksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[playbook.ListPlaybooksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[playbook.Playbook]: + for page in self.pages: + yield from page.playbooks + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPlaybooksAsyncPager: + """A pager for iterating through ``list_playbooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``playbooks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPlaybooks`` requests and continue to iterate + through the ``playbooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse` + attributes are available on the 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[playbook.ListPlaybooksResponse]], + request: playbook.ListPlaybooksRequest, + response: playbook.ListPlaybooksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPlaybooksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = playbook.ListPlaybooksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[playbook.ListPlaybooksResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[playbook.Playbook]: + async def async_generator(): + async for page in self.pages: + for response in page.playbooks: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPlaybookVersionsPager: + """A pager for iterating through ``list_playbook_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``playbook_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPlaybookVersions`` requests and continue to iterate + through the ``playbook_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., playbook.ListPlaybookVersionsResponse], + request: playbook.ListPlaybookVersionsRequest, + response: playbook.ListPlaybookVersionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = playbook.ListPlaybookVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[playbook.ListPlaybookVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[playbook.PlaybookVersion]: + for page in self.pages: + yield from page.playbook_versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPlaybookVersionsAsyncPager: + """A pager for iterating through ``list_playbook_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``playbook_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPlaybookVersions`` requests and continue to iterate + through the ``playbook_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse` + attributes are available on the 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[playbook.ListPlaybookVersionsResponse]], + request: playbook.ListPlaybookVersionsRequest, + response: playbook.ListPlaybookVersionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = playbook.ListPlaybookVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[playbook.ListPlaybookVersionsResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[playbook.PlaybookVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.playbook_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/README.rst b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/README.rst new file mode 100644 index 000000000000..86cc8ac1f27f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PlaybooksTransport` is the ABC for all transports. +- public child `PlaybooksGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PlaybooksGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePlaybooksRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PlaybooksRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/__init__.py new file mode 100644 index 000000000000..a227fbf316f2 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 PlaybooksTransport +from .grpc import PlaybooksGrpcTransport +from .grpc_asyncio import PlaybooksGrpcAsyncIOTransport +from .rest import PlaybooksRestInterceptor, PlaybooksRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PlaybooksTransport]] +_transport_registry["grpc"] = PlaybooksGrpcTransport +_transport_registry["grpc_asyncio"] = PlaybooksGrpcAsyncIOTransport +_transport_registry["rest"] = PlaybooksRestTransport + +__all__ = ( + "PlaybooksTransport", + "PlaybooksGrpcTransport", + "PlaybooksGrpcAsyncIOTransport", + "PlaybooksRestTransport", + "PlaybooksRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/base.py new file mode 100644 index 000000000000..4b4585230edc --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/base.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PlaybooksTransport(abc.ABC): + """Abstract transport class for Playbooks.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_playbook: gapic_v1.method.wrap_method( + self.create_playbook, + default_timeout=None, + client_info=client_info, + ), + self.delete_playbook: gapic_v1.method.wrap_method( + self.delete_playbook, + default_timeout=None, + client_info=client_info, + ), + self.list_playbooks: gapic_v1.method.wrap_method( + self.list_playbooks, + default_timeout=None, + client_info=client_info, + ), + self.get_playbook: gapic_v1.method.wrap_method( + self.get_playbook, + default_timeout=None, + client_info=client_info, + ), + self.export_playbook: gapic_v1.method.wrap_method( + self.export_playbook, + default_timeout=None, + client_info=client_info, + ), + self.import_playbook: gapic_v1.method.wrap_method( + self.import_playbook, + default_timeout=None, + client_info=client_info, + ), + self.update_playbook: gapic_v1.method.wrap_method( + self.update_playbook, + default_timeout=None, + client_info=client_info, + ), + self.create_playbook_version: gapic_v1.method.wrap_method( + self.create_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.get_playbook_version: gapic_v1.method.wrap_method( + self.get_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_playbook_version: gapic_v1.method.wrap_method( + self.restore_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.list_playbook_versions: gapic_v1.method.wrap_method( + self.list_playbook_versions, + default_timeout=None, + client_info=client_info, + ), + self.delete_playbook_version: gapic_v1.method.wrap_method( + self.delete_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_playbook( + self, + ) -> Callable[ + [gcdc_playbook.CreatePlaybookRequest], + Union[gcdc_playbook.Playbook, Awaitable[gcdc_playbook.Playbook]], + ]: + raise NotImplementedError() + + @property + def delete_playbook( + self, + ) -> Callable[ + [playbook.DeletePlaybookRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_playbooks( + self, + ) -> Callable[ + [playbook.ListPlaybooksRequest], + Union[ + playbook.ListPlaybooksResponse, Awaitable[playbook.ListPlaybooksResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_playbook( + self, + ) -> Callable[ + [playbook.GetPlaybookRequest], + Union[playbook.Playbook, Awaitable[playbook.Playbook]], + ]: + raise NotImplementedError() + + @property + def export_playbook( + self, + ) -> Callable[ + [playbook.ExportPlaybookRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def import_playbook( + self, + ) -> Callable[ + [playbook.ImportPlaybookRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_playbook( + self, + ) -> Callable[ + [gcdc_playbook.UpdatePlaybookRequest], + Union[gcdc_playbook.Playbook, Awaitable[gcdc_playbook.Playbook]], + ]: + raise NotImplementedError() + + @property + def create_playbook_version( + self, + ) -> Callable[ + [playbook.CreatePlaybookVersionRequest], + Union[playbook.PlaybookVersion, Awaitable[playbook.PlaybookVersion]], + ]: + raise NotImplementedError() + + @property + def get_playbook_version( + self, + ) -> Callable[ + [playbook.GetPlaybookVersionRequest], + Union[playbook.PlaybookVersion, Awaitable[playbook.PlaybookVersion]], + ]: + raise NotImplementedError() + + @property + def restore_playbook_version( + self, + ) -> Callable[ + [playbook.RestorePlaybookVersionRequest], + Union[ + playbook.RestorePlaybookVersionResponse, + Awaitable[playbook.RestorePlaybookVersionResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_playbook_versions( + self, + ) -> Callable[ + [playbook.ListPlaybookVersionsRequest], + Union[ + playbook.ListPlaybookVersionsResponse, + Awaitable[playbook.ListPlaybookVersionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_playbook_version( + self, + ) -> Callable[ + [playbook.DeletePlaybookVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PlaybooksTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc.py new file mode 100644 index 000000000000..344b36caaedb --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc.py @@ -0,0 +1,766 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .base import DEFAULT_CLIENT_INFO, PlaybooksTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PlaybooksGrpcTransport(PlaybooksTransport): + """gRPC backend transport for Playbooks. + + Service for managing + [Playbooks][google.cloud.dialogflow.cx.v3.Playbook]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_playbook( + self, + ) -> Callable[[gcdc_playbook.CreatePlaybookRequest], gcdc_playbook.Playbook]: + r"""Return a callable for the create playbook method over gRPC. + + Creates a playbook in a specified agent. + + Returns: + Callable[[~.CreatePlaybookRequest], + ~.Playbook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["create_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/CreatePlaybook", + request_serializer=gcdc_playbook.CreatePlaybookRequest.serialize, + response_deserializer=gcdc_playbook.Playbook.deserialize, + ) + return self._stubs["create_playbook"] + + @property + def delete_playbook( + self, + ) -> Callable[[playbook.DeletePlaybookRequest], empty_pb2.Empty]: + r"""Return a callable for the delete playbook method over gRPC. + + Deletes a specified playbook. + + Returns: + Callable[[~.DeletePlaybookRequest], + ~.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_playbook" not in self._stubs: + self._stubs["delete_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/DeletePlaybook", + request_serializer=playbook.DeletePlaybookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_playbook"] + + @property + def list_playbooks( + self, + ) -> Callable[[playbook.ListPlaybooksRequest], playbook.ListPlaybooksResponse]: + r"""Return a callable for the list playbooks method over gRPC. + + Returns a list of playbooks in the specified agent. + + Returns: + Callable[[~.ListPlaybooksRequest], + ~.ListPlaybooksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_playbooks" not in self._stubs: + self._stubs["list_playbooks"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ListPlaybooks", + request_serializer=playbook.ListPlaybooksRequest.serialize, + response_deserializer=playbook.ListPlaybooksResponse.deserialize, + ) + return self._stubs["list_playbooks"] + + @property + def get_playbook( + self, + ) -> Callable[[playbook.GetPlaybookRequest], playbook.Playbook]: + r"""Return a callable for the get playbook method over gRPC. + + Retrieves the specified Playbook. + + Returns: + Callable[[~.GetPlaybookRequest], + ~.Playbook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_playbook" not in self._stubs: + self._stubs["get_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/GetPlaybook", + request_serializer=playbook.GetPlaybookRequest.serialize, + response_deserializer=playbook.Playbook.deserialize, + ) + return self._stubs["get_playbook"] + + @property + def export_playbook( + self, + ) -> Callable[[playbook.ExportPlaybookRequest], operations_pb2.Operation]: + r"""Return a callable for the export playbook method over gRPC. + + Exports the specified playbook to a binary file. + + Note that resources (e.g. examples, tools) that the + playbook references will also be exported. + + Returns: + Callable[[~.ExportPlaybookRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["export_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ExportPlaybook", + request_serializer=playbook.ExportPlaybookRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_playbook"] + + @property + def import_playbook( + self, + ) -> Callable[[playbook.ImportPlaybookRequest], operations_pb2.Operation]: + r"""Return a callable for the import playbook method over gRPC. + + Imports the specified playbook to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportPlaybookRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["import_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ImportPlaybook", + request_serializer=playbook.ImportPlaybookRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_playbook"] + + @property + def update_playbook( + self, + ) -> Callable[[gcdc_playbook.UpdatePlaybookRequest], gcdc_playbook.Playbook]: + r"""Return a callable for the update playbook method over gRPC. + + Updates the specified Playbook. + + Returns: + Callable[[~.UpdatePlaybookRequest], + ~.Playbook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["update_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/UpdatePlaybook", + request_serializer=gcdc_playbook.UpdatePlaybookRequest.serialize, + response_deserializer=gcdc_playbook.Playbook.deserialize, + ) + return self._stubs["update_playbook"] + + @property + def create_playbook_version( + self, + ) -> Callable[[playbook.CreatePlaybookVersionRequest], playbook.PlaybookVersion]: + r"""Return a callable for the create playbook version method over gRPC. + + Creates a version for the specified Playbook. + + Returns: + Callable[[~.CreatePlaybookVersionRequest], + ~.PlaybookVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook_version" not in self._stubs: + self._stubs["create_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/CreatePlaybookVersion", + request_serializer=playbook.CreatePlaybookVersionRequest.serialize, + response_deserializer=playbook.PlaybookVersion.deserialize, + ) + return self._stubs["create_playbook_version"] + + @property + def get_playbook_version( + self, + ) -> Callable[[playbook.GetPlaybookVersionRequest], playbook.PlaybookVersion]: + r"""Return a callable for the get playbook version method over gRPC. + + Retrieves the specified version of the Playbook. + + Returns: + Callable[[~.GetPlaybookVersionRequest], + ~.PlaybookVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_playbook_version" not in self._stubs: + self._stubs["get_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/GetPlaybookVersion", + request_serializer=playbook.GetPlaybookVersionRequest.serialize, + response_deserializer=playbook.PlaybookVersion.deserialize, + ) + return self._stubs["get_playbook_version"] + + @property + def restore_playbook_version( + self, + ) -> Callable[ + [playbook.RestorePlaybookVersionRequest], + playbook.RestorePlaybookVersionResponse, + ]: + r"""Return a callable for the restore playbook version method over gRPC. + + Retrieves the specified version of the Playbook and + stores it as the current playbook draft, returning the + playbook with resources updated. + + Returns: + Callable[[~.RestorePlaybookVersionRequest], + ~.RestorePlaybookVersionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook_version" not in self._stubs: + self._stubs["restore_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/RestorePlaybookVersion", + request_serializer=playbook.RestorePlaybookVersionRequest.serialize, + response_deserializer=playbook.RestorePlaybookVersionResponse.deserialize, + ) + return self._stubs["restore_playbook_version"] + + @property + def list_playbook_versions( + self, + ) -> Callable[ + [playbook.ListPlaybookVersionsRequest], playbook.ListPlaybookVersionsResponse + ]: + r"""Return a callable for the list playbook versions method over gRPC. + + Lists versions for the specified Playbook. + + Returns: + Callable[[~.ListPlaybookVersionsRequest], + ~.ListPlaybookVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_playbook_versions" not in self._stubs: + self._stubs["list_playbook_versions"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ListPlaybookVersions", + request_serializer=playbook.ListPlaybookVersionsRequest.serialize, + response_deserializer=playbook.ListPlaybookVersionsResponse.deserialize, + ) + return self._stubs["list_playbook_versions"] + + @property + def delete_playbook_version( + self, + ) -> Callable[[playbook.DeletePlaybookVersionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete playbook version method over gRPC. + + Deletes the specified version of the Playbook. + + Returns: + Callable[[~.DeletePlaybookVersionRequest], + ~.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_playbook_version" not in self._stubs: + self._stubs["delete_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/DeletePlaybookVersion", + request_serializer=playbook.DeletePlaybookVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_playbook_version"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PlaybooksGrpcTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e0f328378aa4 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/grpc_asyncio.py @@ -0,0 +1,884 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .base import DEFAULT_CLIENT_INFO, PlaybooksTransport +from .grpc import PlaybooksGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PlaybooksGrpcAsyncIOTransport(PlaybooksTransport): + """gRPC AsyncIO backend transport for Playbooks. + + Service for managing + [Playbooks][google.cloud.dialogflow.cx.v3.Playbook]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_playbook( + self, + ) -> Callable[ + [gcdc_playbook.CreatePlaybookRequest], Awaitable[gcdc_playbook.Playbook] + ]: + r"""Return a callable for the create playbook method over gRPC. + + Creates a playbook in a specified agent. + + Returns: + Callable[[~.CreatePlaybookRequest], + Awaitable[~.Playbook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["create_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/CreatePlaybook", + request_serializer=gcdc_playbook.CreatePlaybookRequest.serialize, + response_deserializer=gcdc_playbook.Playbook.deserialize, + ) + return self._stubs["create_playbook"] + + @property + def delete_playbook( + self, + ) -> Callable[[playbook.DeletePlaybookRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete playbook method over gRPC. + + Deletes a specified playbook. + + Returns: + Callable[[~.DeletePlaybookRequest], + 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_playbook" not in self._stubs: + self._stubs["delete_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/DeletePlaybook", + request_serializer=playbook.DeletePlaybookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_playbook"] + + @property + def list_playbooks( + self, + ) -> Callable[ + [playbook.ListPlaybooksRequest], Awaitable[playbook.ListPlaybooksResponse] + ]: + r"""Return a callable for the list playbooks method over gRPC. + + Returns a list of playbooks in the specified agent. + + Returns: + Callable[[~.ListPlaybooksRequest], + Awaitable[~.ListPlaybooksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_playbooks" not in self._stubs: + self._stubs["list_playbooks"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ListPlaybooks", + request_serializer=playbook.ListPlaybooksRequest.serialize, + response_deserializer=playbook.ListPlaybooksResponse.deserialize, + ) + return self._stubs["list_playbooks"] + + @property + def get_playbook( + self, + ) -> Callable[[playbook.GetPlaybookRequest], Awaitable[playbook.Playbook]]: + r"""Return a callable for the get playbook method over gRPC. + + Retrieves the specified Playbook. + + Returns: + Callable[[~.GetPlaybookRequest], + Awaitable[~.Playbook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_playbook" not in self._stubs: + self._stubs["get_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/GetPlaybook", + request_serializer=playbook.GetPlaybookRequest.serialize, + response_deserializer=playbook.Playbook.deserialize, + ) + return self._stubs["get_playbook"] + + @property + def export_playbook( + self, + ) -> Callable[ + [playbook.ExportPlaybookRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the export playbook method over gRPC. + + Exports the specified playbook to a binary file. + + Note that resources (e.g. examples, tools) that the + playbook references will also be exported. + + Returns: + Callable[[~.ExportPlaybookRequest], + 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_playbook" not in self._stubs: + self._stubs["export_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ExportPlaybook", + request_serializer=playbook.ExportPlaybookRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_playbook"] + + @property + def import_playbook( + self, + ) -> Callable[ + [playbook.ImportPlaybookRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the import playbook method over gRPC. + + Imports the specified playbook to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportPlaybookRequest], + 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_playbook" not in self._stubs: + self._stubs["import_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ImportPlaybook", + request_serializer=playbook.ImportPlaybookRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_playbook"] + + @property + def update_playbook( + self, + ) -> Callable[ + [gcdc_playbook.UpdatePlaybookRequest], Awaitable[gcdc_playbook.Playbook] + ]: + r"""Return a callable for the update playbook method over gRPC. + + Updates the specified Playbook. + + Returns: + Callable[[~.UpdatePlaybookRequest], + Awaitable[~.Playbook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook" not in self._stubs: + self._stubs["update_playbook"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/UpdatePlaybook", + request_serializer=gcdc_playbook.UpdatePlaybookRequest.serialize, + response_deserializer=gcdc_playbook.Playbook.deserialize, + ) + return self._stubs["update_playbook"] + + @property + def create_playbook_version( + self, + ) -> Callable[ + [playbook.CreatePlaybookVersionRequest], Awaitable[playbook.PlaybookVersion] + ]: + r"""Return a callable for the create playbook version method over gRPC. + + Creates a version for the specified Playbook. + + Returns: + Callable[[~.CreatePlaybookVersionRequest], + Awaitable[~.PlaybookVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook_version" not in self._stubs: + self._stubs["create_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/CreatePlaybookVersion", + request_serializer=playbook.CreatePlaybookVersionRequest.serialize, + response_deserializer=playbook.PlaybookVersion.deserialize, + ) + return self._stubs["create_playbook_version"] + + @property + def get_playbook_version( + self, + ) -> Callable[ + [playbook.GetPlaybookVersionRequest], Awaitable[playbook.PlaybookVersion] + ]: + r"""Return a callable for the get playbook version method over gRPC. + + Retrieves the specified version of the Playbook. + + Returns: + Callable[[~.GetPlaybookVersionRequest], + Awaitable[~.PlaybookVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_playbook_version" not in self._stubs: + self._stubs["get_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/GetPlaybookVersion", + request_serializer=playbook.GetPlaybookVersionRequest.serialize, + response_deserializer=playbook.PlaybookVersion.deserialize, + ) + return self._stubs["get_playbook_version"] + + @property + def restore_playbook_version( + self, + ) -> Callable[ + [playbook.RestorePlaybookVersionRequest], + Awaitable[playbook.RestorePlaybookVersionResponse], + ]: + r"""Return a callable for the restore playbook version method over gRPC. + + Retrieves the specified version of the Playbook and + stores it as the current playbook draft, returning the + playbook with resources updated. + + Returns: + Callable[[~.RestorePlaybookVersionRequest], + Awaitable[~.RestorePlaybookVersionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_playbook_version" not in self._stubs: + self._stubs["restore_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/RestorePlaybookVersion", + request_serializer=playbook.RestorePlaybookVersionRequest.serialize, + response_deserializer=playbook.RestorePlaybookVersionResponse.deserialize, + ) + return self._stubs["restore_playbook_version"] + + @property + def list_playbook_versions( + self, + ) -> Callable[ + [playbook.ListPlaybookVersionsRequest], + Awaitable[playbook.ListPlaybookVersionsResponse], + ]: + r"""Return a callable for the list playbook versions method over gRPC. + + Lists versions for the specified Playbook. + + Returns: + Callable[[~.ListPlaybookVersionsRequest], + Awaitable[~.ListPlaybookVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_playbook_versions" not in self._stubs: + self._stubs["list_playbook_versions"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/ListPlaybookVersions", + request_serializer=playbook.ListPlaybookVersionsRequest.serialize, + response_deserializer=playbook.ListPlaybookVersionsResponse.deserialize, + ) + return self._stubs["list_playbook_versions"] + + @property + def delete_playbook_version( + self, + ) -> Callable[[playbook.DeletePlaybookVersionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete playbook version method over gRPC. + + Deletes the specified version of the Playbook. + + Returns: + Callable[[~.DeletePlaybookVersionRequest], + 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_playbook_version" not in self._stubs: + self._stubs["delete_playbook_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Playbooks/DeletePlaybookVersion", + request_serializer=playbook.DeletePlaybookVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_playbook_version"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_playbook: self._wrap_method( + self.create_playbook, + default_timeout=None, + client_info=client_info, + ), + self.delete_playbook: self._wrap_method( + self.delete_playbook, + default_timeout=None, + client_info=client_info, + ), + self.list_playbooks: self._wrap_method( + self.list_playbooks, + default_timeout=None, + client_info=client_info, + ), + self.get_playbook: self._wrap_method( + self.get_playbook, + default_timeout=None, + client_info=client_info, + ), + self.export_playbook: self._wrap_method( + self.export_playbook, + default_timeout=None, + client_info=client_info, + ), + self.import_playbook: self._wrap_method( + self.import_playbook, + default_timeout=None, + client_info=client_info, + ), + self.update_playbook: self._wrap_method( + self.update_playbook, + default_timeout=None, + client_info=client_info, + ), + self.create_playbook_version: self._wrap_method( + self.create_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.get_playbook_version: self._wrap_method( + self.get_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_playbook_version: self._wrap_method( + self.restore_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.list_playbook_versions: self._wrap_method( + self.list_playbook_versions, + default_timeout=None, + client_info=client_info, + ), + self.delete_playbook_version: self._wrap_method( + self.delete_playbook_version, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("PlaybooksGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest.py new file mode 100644 index 000000000000..c1846e6cde15 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest.py @@ -0,0 +1,3542 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePlaybooksRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PlaybooksRestInterceptor: + """Interceptor for Playbooks. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PlaybooksRestTransport. + + .. code-block:: python + class MyCustomPlaybooksInterceptor(PlaybooksRestInterceptor): + def pre_create_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_playbook(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_playbook_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_playbook_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_playbook_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_export_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_playbook(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_playbook(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_playbook_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_playbook_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_playbook(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_playbooks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_playbooks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_playbook_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_playbook_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_playbook_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_playbook_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_playbook(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_playbook(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PlaybooksRestTransport(interceptor=MyCustomPlaybooksInterceptor()) + client = PlaybooksClient(transport=transport) + + + """ + + def pre_create_playbook( + self, + request: gcdc_playbook.CreatePlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcdc_playbook.CreatePlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_create_playbook( + self, response: gcdc_playbook.Playbook + ) -> gcdc_playbook.Playbook: + """Post-rpc interceptor for create_playbook + + DEPRECATED. Please use the `post_create_playbook_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_create_playbook` interceptor runs + before the `post_create_playbook_with_metadata` interceptor. + """ + return response + + def post_create_playbook_with_metadata( + self, + response: gcdc_playbook.Playbook, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_playbook.Playbook, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_playbook + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_create_playbook_with_metadata` + interceptor in new development instead of the `post_create_playbook` interceptor. + When both interceptors are used, this `post_create_playbook_with_metadata` interceptor runs after the + `post_create_playbook` interceptor. The (possibly modified) response returned by + `post_create_playbook` will be passed to + `post_create_playbook_with_metadata`. + """ + return response, metadata + + def pre_create_playbook_version( + self, + request: playbook.CreatePlaybookVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.CreatePlaybookVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_playbook_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_create_playbook_version( + self, response: playbook.PlaybookVersion + ) -> playbook.PlaybookVersion: + """Post-rpc interceptor for create_playbook_version + + DEPRECATED. Please use the `post_create_playbook_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_create_playbook_version` interceptor runs + before the `post_create_playbook_version_with_metadata` interceptor. + """ + return response + + def post_create_playbook_version_with_metadata( + self, + response: playbook.PlaybookVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.PlaybookVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_playbook_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_create_playbook_version_with_metadata` + interceptor in new development instead of the `post_create_playbook_version` interceptor. + When both interceptors are used, this `post_create_playbook_version_with_metadata` interceptor runs after the + `post_create_playbook_version` interceptor. The (possibly modified) response returned by + `post_create_playbook_version` will be passed to + `post_create_playbook_version_with_metadata`. + """ + return response, metadata + + def pre_delete_playbook( + self, + request: playbook.DeletePlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.DeletePlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def pre_delete_playbook_version( + self, + request: playbook.DeletePlaybookVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.DeletePlaybookVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_playbook_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def pre_export_playbook( + self, + request: playbook.ExportPlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.ExportPlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_export_playbook( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for export_playbook + + DEPRECATED. Please use the `post_export_playbook_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_export_playbook` interceptor runs + before the `post_export_playbook_with_metadata` interceptor. + """ + return response + + def post_export_playbook_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_playbook + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_export_playbook_with_metadata` + interceptor in new development instead of the `post_export_playbook` interceptor. + When both interceptors are used, this `post_export_playbook_with_metadata` interceptor runs after the + `post_export_playbook` interceptor. The (possibly modified) response returned by + `post_export_playbook` will be passed to + `post_export_playbook_with_metadata`. + """ + return response, metadata + + def pre_get_playbook( + self, + request: playbook.GetPlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.GetPlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_get_playbook(self, response: playbook.Playbook) -> playbook.Playbook: + """Post-rpc interceptor for get_playbook + + DEPRECATED. Please use the `post_get_playbook_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_get_playbook` interceptor runs + before the `post_get_playbook_with_metadata` interceptor. + """ + return response + + def post_get_playbook_with_metadata( + self, + response: playbook.Playbook, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.Playbook, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_playbook + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_get_playbook_with_metadata` + interceptor in new development instead of the `post_get_playbook` interceptor. + When both interceptors are used, this `post_get_playbook_with_metadata` interceptor runs after the + `post_get_playbook` interceptor. The (possibly modified) response returned by + `post_get_playbook` will be passed to + `post_get_playbook_with_metadata`. + """ + return response, metadata + + def pre_get_playbook_version( + self, + request: playbook.GetPlaybookVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.GetPlaybookVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_playbook_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_get_playbook_version( + self, response: playbook.PlaybookVersion + ) -> playbook.PlaybookVersion: + """Post-rpc interceptor for get_playbook_version + + DEPRECATED. Please use the `post_get_playbook_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_get_playbook_version` interceptor runs + before the `post_get_playbook_version_with_metadata` interceptor. + """ + return response + + def post_get_playbook_version_with_metadata( + self, + response: playbook.PlaybookVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.PlaybookVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_playbook_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_get_playbook_version_with_metadata` + interceptor in new development instead of the `post_get_playbook_version` interceptor. + When both interceptors are used, this `post_get_playbook_version_with_metadata` interceptor runs after the + `post_get_playbook_version` interceptor. The (possibly modified) response returned by + `post_get_playbook_version` will be passed to + `post_get_playbook_version_with_metadata`. + """ + return response, metadata + + def pre_import_playbook( + self, + request: playbook.ImportPlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.ImportPlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for import_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_import_playbook( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_playbook + + DEPRECATED. Please use the `post_import_playbook_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_import_playbook` interceptor runs + before the `post_import_playbook_with_metadata` interceptor. + """ + return response + + def post_import_playbook_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_playbook + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_import_playbook_with_metadata` + interceptor in new development instead of the `post_import_playbook` interceptor. + When both interceptors are used, this `post_import_playbook_with_metadata` interceptor runs after the + `post_import_playbook` interceptor. The (possibly modified) response returned by + `post_import_playbook` will be passed to + `post_import_playbook_with_metadata`. + """ + return response, metadata + + def pre_list_playbooks( + self, + request: playbook.ListPlaybooksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.ListPlaybooksRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_playbooks + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_list_playbooks( + self, response: playbook.ListPlaybooksResponse + ) -> playbook.ListPlaybooksResponse: + """Post-rpc interceptor for list_playbooks + + DEPRECATED. Please use the `post_list_playbooks_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_list_playbooks` interceptor runs + before the `post_list_playbooks_with_metadata` interceptor. + """ + return response + + def post_list_playbooks_with_metadata( + self, + response: playbook.ListPlaybooksResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[playbook.ListPlaybooksResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_playbooks + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_list_playbooks_with_metadata` + interceptor in new development instead of the `post_list_playbooks` interceptor. + When both interceptors are used, this `post_list_playbooks_with_metadata` interceptor runs after the + `post_list_playbooks` interceptor. The (possibly modified) response returned by + `post_list_playbooks` will be passed to + `post_list_playbooks_with_metadata`. + """ + return response, metadata + + def pre_list_playbook_versions( + self, + request: playbook.ListPlaybookVersionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.ListPlaybookVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_playbook_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_list_playbook_versions( + self, response: playbook.ListPlaybookVersionsResponse + ) -> playbook.ListPlaybookVersionsResponse: + """Post-rpc interceptor for list_playbook_versions + + DEPRECATED. Please use the `post_list_playbook_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_list_playbook_versions` interceptor runs + before the `post_list_playbook_versions_with_metadata` interceptor. + """ + return response + + def post_list_playbook_versions_with_metadata( + self, + response: playbook.ListPlaybookVersionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.ListPlaybookVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_playbook_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_list_playbook_versions_with_metadata` + interceptor in new development instead of the `post_list_playbook_versions` interceptor. + When both interceptors are used, this `post_list_playbook_versions_with_metadata` interceptor runs after the + `post_list_playbook_versions` interceptor. The (possibly modified) response returned by + `post_list_playbook_versions` will be passed to + `post_list_playbook_versions_with_metadata`. + """ + return response, metadata + + def pre_restore_playbook_version( + self, + request: playbook.RestorePlaybookVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.RestorePlaybookVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for restore_playbook_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_restore_playbook_version( + self, response: playbook.RestorePlaybookVersionResponse + ) -> playbook.RestorePlaybookVersionResponse: + """Post-rpc interceptor for restore_playbook_version + + DEPRECATED. Please use the `post_restore_playbook_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_restore_playbook_version` interceptor runs + before the `post_restore_playbook_version_with_metadata` interceptor. + """ + return response + + def post_restore_playbook_version_with_metadata( + self, + response: playbook.RestorePlaybookVersionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + playbook.RestorePlaybookVersionResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for restore_playbook_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_restore_playbook_version_with_metadata` + interceptor in new development instead of the `post_restore_playbook_version` interceptor. + When both interceptors are used, this `post_restore_playbook_version_with_metadata` interceptor runs after the + `post_restore_playbook_version` interceptor. The (possibly modified) response returned by + `post_restore_playbook_version` will be passed to + `post_restore_playbook_version_with_metadata`. + """ + return response, metadata + + def pre_update_playbook( + self, + request: gcdc_playbook.UpdatePlaybookRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcdc_playbook.UpdatePlaybookRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_playbook + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_update_playbook( + self, response: gcdc_playbook.Playbook + ) -> gcdc_playbook.Playbook: + """Post-rpc interceptor for update_playbook + + DEPRECATED. Please use the `post_update_playbook_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. This `post_update_playbook` interceptor runs + before the `post_update_playbook_with_metadata` interceptor. + """ + return response + + def post_update_playbook_with_metadata( + self, + response: gcdc_playbook.Playbook, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_playbook.Playbook, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_playbook + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Playbooks server but before it is returned to user code. + + We recommend only using this `post_update_playbook_with_metadata` + interceptor in new development instead of the `post_update_playbook` interceptor. + When both interceptors are used, this `post_update_playbook_with_metadata` interceptor runs after the + `post_update_playbook` interceptor. The (possibly modified) response returned by + `post_update_playbook` will be passed to + `post_update_playbook_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Playbooks server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Playbooks server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PlaybooksRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PlaybooksRestInterceptor + + +class PlaybooksRestTransport(_BasePlaybooksRestTransport): + """REST backend synchronous transport for Playbooks. + + Service for managing + [Playbooks][google.cloud.dialogflow.cx.v3.Playbook]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PlaybooksRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PlaybooksRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v3/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:cancel", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v3/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v3", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreatePlaybook( + _BasePlaybooksRestTransport._BaseCreatePlaybook, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.CreatePlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_playbook.CreatePlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Call the create playbook method over HTTP. + + Args: + request (~.gcdc_playbook.CreatePlaybookRequest): + The request object. The request message for + [Playbooks.CreatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_playbook.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseCreatePlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseCreatePlaybook._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BasePlaybooksRestTransport._BaseCreatePlaybook._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseCreatePlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.CreatePlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "CreatePlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._CreatePlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_playbook.Playbook() + pb_resp = gcdc_playbook.Playbook.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_playbook(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_playbook_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_playbook.Playbook.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.create_playbook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "CreatePlaybook", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreatePlaybookVersion( + _BasePlaybooksRestTransport._BaseCreatePlaybookVersion, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.CreatePlaybookVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: playbook.CreatePlaybookVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Call the create playbook version method over HTTP. + + Args: + request (~.playbook.CreatePlaybookVersionRequest): + The request object. The request message for + [Playbooks.CreatePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_playbook_version( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_transcoded_request( + http_options, request + ) + + body = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.CreatePlaybookVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "CreatePlaybookVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._CreatePlaybookVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.PlaybookVersion() + pb_resp = playbook.PlaybookVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_playbook_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_playbook_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.PlaybookVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.create_playbook_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "CreatePlaybookVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePlaybook( + _BasePlaybooksRestTransport._BaseDeletePlaybook, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.DeletePlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.DeletePlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete playbook method over HTTP. + + Args: + request (~.playbook.DeletePlaybookRequest): + The request object. The request message for + [Playbooks.DeletePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseDeletePlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseDeletePlaybook._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseDeletePlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.DeletePlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "DeletePlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._DeletePlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePlaybookVersion( + _BasePlaybooksRestTransport._BaseDeletePlaybookVersion, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.DeletePlaybookVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.DeletePlaybookVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete playbook version method over HTTP. + + Args: + request (~.playbook.DeletePlaybookVersionRequest): + The request object. The request message for + [Playbooks.DeletePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_playbook_version( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.DeletePlaybookVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "DeletePlaybookVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._DeletePlaybookVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ExportPlaybook( + _BasePlaybooksRestTransport._BaseExportPlaybook, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ExportPlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: playbook.ExportPlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the export playbook method over HTTP. + + Args: + request (~.playbook.ExportPlaybookRequest): + The request object. The request message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseExportPlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_export_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseExportPlaybook._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BasePlaybooksRestTransport._BaseExportPlaybook._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseExportPlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ExportPlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ExportPlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ExportPlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_playbook(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_playbook_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.export_playbook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ExportPlaybook", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPlaybook(_BasePlaybooksRestTransport._BaseGetPlaybook, PlaybooksRestStub): + def __hash__(self): + return hash("PlaybooksRestTransport.GetPlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.GetPlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.Playbook: + r"""Call the get playbook method over HTTP. + + Args: + request (~.playbook.GetPlaybookRequest): + The request object. The request message for + [Playbooks.GetPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseGetPlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseGetPlaybook._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseGetPlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.GetPlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetPlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._GetPlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.Playbook() + pb_resp = playbook.Playbook.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_playbook(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_playbook_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.Playbook.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.get_playbook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetPlaybook", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPlaybookVersion( + _BasePlaybooksRestTransport._BaseGetPlaybookVersion, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.GetPlaybookVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.GetPlaybookVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.PlaybookVersion: + r"""Call the get playbook version method over HTTP. + + Args: + request (~.playbook.GetPlaybookVersionRequest): + The request object. The request message for + [Playbooks.GetPlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.PlaybookVersion: + Playbook version is a snapshot of the + playbook at certain timestamp. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_playbook_version( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.GetPlaybookVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetPlaybookVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._GetPlaybookVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.PlaybookVersion() + pb_resp = playbook.PlaybookVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_playbook_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_playbook_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.PlaybookVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.get_playbook_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetPlaybookVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportPlaybook( + _BasePlaybooksRestTransport._BaseImportPlaybook, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ImportPlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: playbook.ImportPlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the import playbook method over HTTP. + + Args: + request (~.playbook.ImportPlaybookRequest): + The request object. The request message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseImportPlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_import_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseImportPlaybook._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BasePlaybooksRestTransport._BaseImportPlaybook._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseImportPlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ImportPlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ImportPlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ImportPlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_playbook(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_playbook_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.import_playbook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ImportPlaybook", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPlaybooks( + _BasePlaybooksRestTransport._BaseListPlaybooks, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ListPlaybooks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.ListPlaybooksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.ListPlaybooksResponse: + r"""Call the list playbooks method over HTTP. + + Args: + request (~.playbook.ListPlaybooksRequest): + The request object. The request message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.ListPlaybooksResponse: + The response message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseListPlaybooks._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_playbooks(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseListPlaybooks._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseListPlaybooks._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ListPlaybooks", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListPlaybooks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ListPlaybooks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.ListPlaybooksResponse() + pb_resp = playbook.ListPlaybooksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_playbooks(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_playbooks_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.ListPlaybooksResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.list_playbooks", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListPlaybooks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPlaybookVersions( + _BasePlaybooksRestTransport._BaseListPlaybookVersions, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ListPlaybookVersions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: playbook.ListPlaybookVersionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.ListPlaybookVersionsResponse: + r"""Call the list playbook versions method over HTTP. + + Args: + request (~.playbook.ListPlaybookVersionsRequest): + The request object. The request message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.ListPlaybookVersionsResponse: + The response message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_playbook_versions( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ListPlaybookVersions", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListPlaybookVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ListPlaybookVersions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.ListPlaybookVersionsResponse() + pb_resp = playbook.ListPlaybookVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_playbook_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_playbook_versions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.ListPlaybookVersionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.list_playbook_versions", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListPlaybookVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RestorePlaybookVersion( + _BasePlaybooksRestTransport._BaseRestorePlaybookVersion, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.RestorePlaybookVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: playbook.RestorePlaybookVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> playbook.RestorePlaybookVersionResponse: + r"""Call the restore playbook version method over HTTP. + + Args: + request (~.playbook.RestorePlaybookVersionRequest): + The request object. The request message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.playbook.RestorePlaybookVersionResponse: + The response message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseRestorePlaybookVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_restore_playbook_version( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseRestorePlaybookVersion._get_transcoded_request( + http_options, request + ) + + body = _BasePlaybooksRestTransport._BaseRestorePlaybookVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePlaybooksRestTransport._BaseRestorePlaybookVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.RestorePlaybookVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "RestorePlaybookVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._RestorePlaybookVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = playbook.RestorePlaybookVersionResponse() + pb_resp = playbook.RestorePlaybookVersionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_restore_playbook_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restore_playbook_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = playbook.RestorePlaybookVersionResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.restore_playbook_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "RestorePlaybookVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePlaybook( + _BasePlaybooksRestTransport._BaseUpdatePlaybook, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.UpdatePlaybook") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_playbook.UpdatePlaybookRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_playbook.Playbook: + r"""Call the update playbook method over HTTP. + + Args: + request (~.gcdc_playbook.UpdatePlaybookRequest): + The request object. The request message for + [Playbooks.UpdatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_playbook.Playbook: + Playbook is the basic building block + to instruct the LLM how to execute a + certain task. + + A playbook consists of a goal to + accomplish, an optional list of step by + step instructions (the step instruction + may refers to name of the custom or + default plugin tools to use) to perform + the task, a list of contextual input + data to be passed in at the beginning of + the invoked, and a list of output + parameters to store the playbook result. + + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_playbook(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.UpdatePlaybook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "UpdatePlaybook", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._UpdatePlaybook._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_playbook.Playbook() + pb_resp = gcdc_playbook.Playbook.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_playbook(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_playbook_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_playbook.Playbook.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksClient.update_playbook", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "UpdatePlaybook", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_playbook( + self, + ) -> Callable[[gcdc_playbook.CreatePlaybookRequest], gcdc_playbook.Playbook]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_playbook_version( + self, + ) -> Callable[[playbook.CreatePlaybookVersionRequest], playbook.PlaybookVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePlaybookVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_playbook( + self, + ) -> Callable[[playbook.DeletePlaybookRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_playbook_version( + self, + ) -> Callable[[playbook.DeletePlaybookVersionRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePlaybookVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_playbook( + self, + ) -> Callable[[playbook.ExportPlaybookRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportPlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_playbook( + self, + ) -> Callable[[playbook.GetPlaybookRequest], playbook.Playbook]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_playbook_version( + self, + ) -> Callable[[playbook.GetPlaybookVersionRequest], playbook.PlaybookVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPlaybookVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_playbook( + self, + ) -> Callable[[playbook.ImportPlaybookRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportPlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_playbooks( + self, + ) -> Callable[[playbook.ListPlaybooksRequest], playbook.ListPlaybooksResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPlaybooks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_playbook_versions( + self, + ) -> Callable[ + [playbook.ListPlaybookVersionsRequest], playbook.ListPlaybookVersionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPlaybookVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_playbook_version( + self, + ) -> Callable[ + [playbook.RestorePlaybookVersionRequest], + playbook.RestorePlaybookVersionResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestorePlaybookVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_playbook( + self, + ) -> Callable[[gcdc_playbook.UpdatePlaybookRequest], gcdc_playbook.Playbook]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePlaybook(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BasePlaybooksRestTransport._BaseGetLocation, PlaybooksRestStub): + def __hash__(self): + return hash("PlaybooksRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BasePlaybooksRestTransport._BaseListLocations, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BasePlaybooksRestTransport._BaseCancelOperation, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BasePlaybooksRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePlaybooksRestTransport._BaseGetOperation, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BasePlaybooksRestTransport._BaseListOperations, PlaybooksRestStub + ): + def __hash__(self): + return hash("PlaybooksRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BasePlaybooksRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BasePlaybooksRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePlaybooksRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.PlaybooksClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PlaybooksRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.PlaybooksAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Playbooks", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PlaybooksRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest_base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest_base.py new file mode 100644 index 000000000000..f77d10e21ea9 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/playbooks/transports/rest_base.py @@ -0,0 +1,856 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +from .base import DEFAULT_CLIENT_INFO, PlaybooksTransport + + +class _BasePlaybooksRestTransport(PlaybooksTransport): + """Base REST backend transport for Playbooks. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*}/playbooks", + "body": "playbook", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_playbook.CreatePlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseCreatePlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreatePlaybookVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions", + "body": "playbook_version", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.CreatePlaybookVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseCreatePlaybookVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.DeletePlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseDeletePlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePlaybookVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.DeletePlaybookVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseDeletePlaybookVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportPlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*}:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.ExportPlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseExportPlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.GetPlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseGetPlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPlaybookVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.GetPlaybookVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseGetPlaybookVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportPlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*}/playbooks:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.ImportPlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseImportPlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPlaybooks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*/agents/*}/playbooks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.ListPlaybooksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseListPlaybooks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPlaybookVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.ListPlaybookVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseListPlaybookVersions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestorePlaybookVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}:restore", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = playbook.RestorePlaybookVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseRestorePlaybookVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePlaybook: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{playbook.name=projects/*/locations/*/agents/*/playbooks/*}", + "body": "playbook", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_playbook.UpdatePlaybookRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePlaybooksRestTransport._BaseUpdatePlaybook._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePlaybooksRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/async_client.py index 1af4aef0ea47..85dc4065918a 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -94,12 +94,16 @@ class SessionsAsyncClient: parse_intent_path = staticmethod(SessionsClient.parse_intent_path) page_path = staticmethod(SessionsClient.page_path) parse_page_path = staticmethod(SessionsClient.parse_page_path) + playbook_path = staticmethod(SessionsClient.playbook_path) + parse_playbook_path = staticmethod(SessionsClient.parse_playbook_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 ) + tool_path = staticmethod(SessionsClient.tool_path) + parse_tool_path = staticmethod(SessionsClient.parse_tool_path) transition_route_group_path = staticmethod( SessionsClient.transition_route_group_path ) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/client.py index e1e7e3111196..3e5803bd3002 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/sessions/client.py @@ -374,6 +374,30 @@ def parse_page_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def session_path( project: str, @@ -424,6 +448,30 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def transition_route_group_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py index d68e28c0902d..f5dc056b1bf6 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py @@ -98,12 +98,16 @@ class TestCasesAsyncClient: parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) page_path = staticmethod(TestCasesClient.page_path) parse_page_path = staticmethod(TestCasesClient.parse_page_path) + playbook_path = staticmethod(TestCasesClient.playbook_path) + parse_playbook_path = staticmethod(TestCasesClient.parse_playbook_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 ) + tool_path = staticmethod(TestCasesClient.tool_path) + parse_tool_path = staticmethod(TestCasesClient.parse_tool_path) transition_route_group_path = staticmethod( TestCasesClient.transition_route_group_path ) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/client.py index 4ae47bef42a0..20bc5a6ad1b5 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/test_cases/client.py @@ -401,6 +401,30 @@ def parse_page_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def playbook_path( + project: str, + location: str, + agent: str, + playbook: str, + ) -> str: + """Returns a fully-qualified playbook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + + @staticmethod + def parse_playbook_path(path: str) -> Dict[str, str]: + """Parses a playbook path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/playbooks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def test_case_path( project: str, @@ -451,6 +475,30 @@ def parse_test_case_result_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def transition_route_group_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/__init__.py new file mode 100644 index 000000000000..ca7fdb7c7f9d --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import ToolsAsyncClient +from .client import ToolsClient + +__all__ = ( + "ToolsClient", + "ToolsAsyncClient", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/async_client.py new file mode 100644 index 000000000000..2e8e856bfd39 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/async_client.py @@ -0,0 +1,1765 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.tools import pagers +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .client import ToolsClient +from .transports.base import DEFAULT_CLIENT_INFO, ToolsTransport +from .transports.grpc_asyncio import ToolsGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class ToolsAsyncClient: + """Service for managing [Tools][google.cloud.dialogflow.cx.v3.Tool].""" + + _client: ToolsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ToolsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ToolsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ToolsClient._DEFAULT_UNIVERSE + + secret_version_path = staticmethod(ToolsClient.secret_version_path) + parse_secret_version_path = staticmethod(ToolsClient.parse_secret_version_path) + service_path = staticmethod(ToolsClient.service_path) + parse_service_path = staticmethod(ToolsClient.parse_service_path) + tool_path = staticmethod(ToolsClient.tool_path) + parse_tool_path = staticmethod(ToolsClient.parse_tool_path) + tool_version_path = staticmethod(ToolsClient.tool_version_path) + parse_tool_version_path = staticmethod(ToolsClient.parse_tool_version_path) + common_billing_account_path = staticmethod(ToolsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod( + ToolsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ToolsClient.common_folder_path) + parse_common_folder_path = staticmethod(ToolsClient.parse_common_folder_path) + common_organization_path = staticmethod(ToolsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ToolsClient.parse_common_organization_path + ) + common_project_path = staticmethod(ToolsClient.common_project_path) + parse_common_project_path = staticmethod(ToolsClient.parse_common_project_path) + common_location_path = staticmethod(ToolsClient.common_location_path) + parse_common_location_path = staticmethod(ToolsClient.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: + ToolsAsyncClient: The constructed client. + """ + return ToolsClient.from_service_account_info.__func__(ToolsAsyncClient, 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: + ToolsAsyncClient: The constructed client. + """ + return ToolsClient.from_service_account_file.__func__(ToolsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ToolsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ToolsTransport: + """Returns the transport used by the client instance. + + Returns: + ToolsTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = ToolsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ToolsTransport, Callable[..., ToolsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tools async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ToolsTransport,Callable[..., ToolsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ToolsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ToolsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.ToolsAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "credentialsType": None, + }, + ) + + async def create_tool( + self, + request: Optional[Union[gcdc_tool.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcdc_tool.Tool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Creates a [Tool][google.cloud.dialogflow.cx.v3.Tool] in the + specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_create_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = await client.create_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.CreateToolRequest, dict]]): + The request object. The request message for + [Tools.CreateTool][google.cloud.dialogflow.cx.v3.Tools.CreateTool]. + parent (:class:`str`): + Required. The agent to create a Tool for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (:class:`google.cloud.dialogflowcx_v3.types.Tool`): + Required. The Tool to be created. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_tool.CreateToolRequest): + request = gcdc_tool.CreateToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool is not None: + request.tool = tool + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_tools( + self, + request: Optional[Union[tool.ListToolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsAsyncPager: + r"""Returns a list of [Tools][google.cloud.dialogflow.cx.v3.Tool] in + the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_list_tools(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ListToolsRequest, dict]]): + The request object. The request message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + parent (:class:`str`): + Required. The agent to list the Tools 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolsAsyncPager: + The response message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.ListToolsRequest): + request = tool.ListToolsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_tools + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListToolsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tool( + self, + request: Optional[Union[tool.GetToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Retrieves the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_get_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetToolRequest, dict]]): + The request object. The request message for + [Tools.GetTool][google.cloud.dialogflow.cx.v3.Tools.GetTool]. + name (:class:`str`): + Required. The name of the Tool. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.GetToolRequest): + request = tool.GetToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[self._client._transport.get_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_tool( + self, + request: Optional[Union[gcdc_tool.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcdc_tool.Tool] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Update the specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_update_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.UpdateToolRequest, dict]]): + The request object. The request message for + [Tools.UpdateTool][google.cloud.dialogflow.cx.v3.Tools.UpdateTool]. + tool (:class:`google.cloud.dialogflowcx_v3.types.Tool`): + Required. The Tool to be updated. + This corresponds to the ``tool`` 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tool, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_tool.UpdateToolRequest): + request = gcdc_tool.UpdateToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tool is not None: + request.tool = tool + 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._client._transport._wrapped_methods[ + self._client._transport.update_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("tool.name", request.tool.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tool( + self, + request: Optional[Union[tool.DeleteToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_delete_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.DeleteToolRequest, dict]]): + The request object. The request message for + [Tools.DeleteTool][google.cloud.dialogflow.cx.v3.Tools.DeleteTool]. + name (:class:`str`): + Required. The name of the Tool to be deleted. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.DeleteToolRequest): + request = tool.DeleteToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_tool_versions( + self, + request: Optional[Union[tool.ListToolVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolVersionsAsyncPager: + r"""List versions of the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_list_tool_versions(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tool_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest, dict]]): + The request object. The request message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + parent (:class:`str`): + Required. The parent of the tool versions. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolVersionsAsyncPager: + The response message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.ListToolVersionsRequest): + request = tool.ListToolVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_tool_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListToolVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tool_version( + self, + request: Optional[Union[tool.CreateToolVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool_version: Optional[tool.ToolVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Creates a version for the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_create_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool_version = dialogflowcx_v3.ToolVersion() + tool_version.display_name = "display_name_value" + tool_version.tool.open_api_spec.text_schema = "text_schema_value" + tool_version.tool.display_name = "display_name_value" + tool_version.tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolVersionRequest( + parent="parent_value", + tool_version=tool_version, + ) + + # Make the request + response = await client.create_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.CreateToolVersionRequest, dict]]): + The request object. The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + parent (:class:`str`): + Required. The tool to create a version for. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool_version (:class:`google.cloud.dialogflowcx_v3.types.ToolVersion`): + Required. The tool version to create. + This corresponds to the ``tool_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool_version] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.CreateToolVersionRequest): + request = tool.CreateToolVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool_version is not None: + request.tool_version = tool_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_tool_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tool_version( + self, + request: Optional[Union[tool.GetToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Retrieves the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_get_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.GetToolVersionRequest, dict]]): + The request object. The request message for + [Tools.GetToolVersion][google.cloud.dialogflow.cx.v3.Tools.GetToolVersion]. + name (:class:`str`): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.GetToolVersionRequest): + request = tool.GetToolVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_tool_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tool_version( + self, + request: Optional[Union[tool.DeleteToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_delete_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool_version(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.DeleteToolVersionRequest, dict]]): + The request object. The request message for + [Tools.DeleteToolVersion][google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion]. + name (:class:`str`): + Required. The name of the tool version to delete. + Format: + ``projects//locations//agents//tools//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.DeleteToolVersionRequest): + request = tool.DeleteToolVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_tool_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def restore_tool_version( + self, + request: Optional[Union[tool.RestoreToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.RestoreToolVersionResponse: + r"""Retrieves the specified version of the Tool and + stores it as the current tool draft, returning the tool + with resources updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + async def sample_restore_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestoreToolVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflowcx_v3.types.RestoreToolVersionRequest, dict]]): + The request object. The request message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + name (:class:`str`): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.RestoreToolVersionResponse: + The response message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.RestoreToolVersionRequest): + request = tool.RestoreToolVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.restore_tool_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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ToolsAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("ToolsAsyncClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/client.py new file mode 100644 index 000000000000..005df8ddf4b3 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/client.py @@ -0,0 +1,2273 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.tools import pagers +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .transports.base import DEFAULT_CLIENT_INFO, ToolsTransport +from .transports.grpc import ToolsGrpcTransport +from .transports.grpc_asyncio import ToolsGrpcAsyncIOTransport +from .transports.rest import ToolsRestTransport + + +class ToolsClientMeta(type): + """Metaclass for the Tools 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[ToolsTransport]] + _transport_registry["grpc"] = ToolsGrpcTransport + _transport_registry["grpc_asyncio"] = ToolsGrpcAsyncIOTransport + _transport_registry["rest"] = ToolsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ToolsTransport]: + """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 ToolsClient(metaclass=ToolsClientMeta): + """Service for managing [Tools][google.cloud.dialogflow.cx.v3.Tool].""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ToolsClient: 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: + ToolsClient: 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) -> ToolsTransport: + """Returns the transport used by the client instance. + + Returns: + ToolsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def secret_version_path( + project: str, + secret: str, + version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @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 tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_version_path( + project: str, + location: str, + agent: str, + tool: str, + version: str, + ) -> str: + """Returns a fully-qualified tool_version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}/versions/{version}".format( + project=project, + location=location, + agent=agent, + tool=tool, + version=version, + ) + + @staticmethod + def parse_tool_version_path(path: str) -> Dict[str, str]: + """Parses a tool_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ToolsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ToolsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ToolsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ToolsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ToolsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ToolsTransport, Callable[..., ToolsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tools client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ToolsTransport,Callable[..., ToolsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ToolsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ToolsClient._read_environment_variables() + self._client_cert_source = ToolsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ToolsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ToolsTransport) + if transport_provided: + # transport is a ToolsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ToolsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ToolsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ToolsTransport], Callable[..., ToolsTransport] + ] = ( + ToolsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ToolsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.dialogflow.cx_v3.ToolsClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "credentialsType": None, + }, + ) + + def create_tool( + self, + request: Optional[Union[gcdc_tool.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcdc_tool.Tool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Creates a [Tool][google.cloud.dialogflow.cx.v3.Tool] in the + specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_create_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = client.create_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateToolRequest, dict]): + The request object. The request message for + [Tools.CreateTool][google.cloud.dialogflow.cx.v3.Tools.CreateTool]. + parent (str): + Required. The agent to create a Tool for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (google.cloud.dialogflowcx_v3.types.Tool): + Required. The Tool to be created. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_tool.CreateToolRequest): + request = gcdc_tool.CreateToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool is not None: + request.tool = tool + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_tools( + self, + request: Optional[Union[tool.ListToolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsPager: + r"""Returns a list of [Tools][google.cloud.dialogflow.cx.v3.Tool] in + the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_list_tools(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListToolsRequest, dict]): + The request object. The request message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + parent (str): + Required. The agent to list the Tools 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolsPager: + The response message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.ListToolsRequest): + request = tool.ListToolsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListToolsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tool( + self, + request: Optional[Union[tool.GetToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Retrieves the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_get_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetToolRequest, dict]): + The request object. The request message for + [Tools.GetTool][google.cloud.dialogflow.cx.v3.Tools.GetTool]. + name (str): + Required. The name of the Tool. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.GetToolRequest): + request = tool.GetToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_tool( + self, + request: Optional[Union[gcdc_tool.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcdc_tool.Tool] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Update the specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_update_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateToolRequest, dict]): + The request object. The request message for + [Tools.UpdateTool][google.cloud.dialogflow.cx.v3.Tools.UpdateTool]. + tool (google.cloud.dialogflowcx_v3.types.Tool): + Required. The Tool to be updated. + This corresponds to the ``tool`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.Tool: + A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to + attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool + which contains the schema and authentication + information. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tool, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcdc_tool.UpdateToolRequest): + request = gcdc_tool.UpdateToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tool is not None: + request.tool = tool + 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_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("tool.name", request.tool.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tool( + self, + request: Optional[Union[tool.DeleteToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_delete_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteToolRequest, dict]): + The request object. The request message for + [Tools.DeleteTool][google.cloud.dialogflow.cx.v3.Tools.DeleteTool]. + name (str): + Required. The name of the Tool to be deleted. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.DeleteToolRequest): + request = tool.DeleteToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_tool_versions( + self, + request: Optional[Union[tool.ListToolVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolVersionsPager: + r"""List versions of the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_list_tool_versions(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tool_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest, dict]): + The request object. The request message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + parent (str): + Required. The parent of the tool versions. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolVersionsPager: + The response message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.ListToolVersionsRequest): + request = tool.ListToolVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tool_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListToolVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tool_version( + self, + request: Optional[Union[tool.CreateToolVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool_version: Optional[tool.ToolVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Creates a version for the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_create_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool_version = dialogflowcx_v3.ToolVersion() + tool_version.display_name = "display_name_value" + tool_version.tool.open_api_spec.text_schema = "text_schema_value" + tool_version.tool.display_name = "display_name_value" + tool_version.tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolVersionRequest( + parent="parent_value", + tool_version=tool_version, + ) + + # Make the request + response = client.create_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateToolVersionRequest, dict]): + The request object. The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + parent (str): + Required. The tool to create a version for. Format: + ``projects//locations//agents//tools/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool_version (google.cloud.dialogflowcx_v3.types.ToolVersion): + Required. The tool version to create. + This corresponds to the ``tool_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool_version] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.CreateToolVersionRequest): + request = tool.CreateToolVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool_version is not None: + request.tool_version = tool_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tool_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tool_version( + self, + request: Optional[Union[tool.GetToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Retrieves the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_get_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetToolVersionRequest, dict]): + The request object. The request message for + [Tools.GetToolVersion][google.cloud.dialogflow.cx.v3.Tools.GetToolVersion]. + name (str): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.GetToolVersionRequest): + request = tool.GetToolVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tool_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tool_version( + self, + request: Optional[Union[tool.DeleteToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_delete_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_tool_version(request=request) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteToolVersionRequest, dict]): + The request object. The request message for + [Tools.DeleteToolVersion][google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion]. + name (str): + Required. The name of the tool version to delete. + Format: + ``projects//locations//agents//tools//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.DeleteToolVersionRequest): + request = tool.DeleteToolVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_tool_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def restore_tool_version( + self, + request: Optional[Union[tool.RestoreToolVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.RestoreToolVersionResponse: + r"""Retrieves the specified version of the Tool and + stores it as the current tool draft, returning the tool + with resources updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import dialogflowcx_v3 + + def sample_restore_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestoreToolVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_tool_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.RestoreToolVersionRequest, dict]): + The request object. The request message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + name (str): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.dialogflowcx_v3.types.RestoreToolVersionResponse: + The response message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool.RestoreToolVersionRequest): + request = tool.RestoreToolVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.restore_tool_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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ToolsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ToolsClient",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/pagers.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/pagers.py new file mode 100644 index 000000000000..b535f268cbd7 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/pagers.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.dialogflowcx_v3.types import tool + + +class ListToolsPager: + """A pager for iterating through ``list_tools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListToolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTools`` requests and continue to iterate + through the ``tools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListToolsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., tool.ListToolsResponse], + request: tool.ListToolsRequest, + response: tool.ListToolsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListToolsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListToolsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = tool.ListToolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tool.ListToolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[tool.Tool]: + for page in self.pages: + yield from page.tools + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolsAsyncPager: + """A pager for iterating through ``list_tools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListToolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTools`` requests and continue to iterate + through the ``tools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListToolsResponse` + attributes are available on the 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[tool.ListToolsResponse]], + request: tool.ListToolsRequest, + response: tool.ListToolsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListToolsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListToolsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = tool.ListToolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tool.ListToolsResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[tool.Tool]: + async def async_generator(): + async for page in self.pages: + for response in page.tools: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolVersionsPager: + """A pager for iterating through ``list_tool_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tool_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListToolVersions`` requests and continue to iterate + through the ``tool_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., tool.ListToolVersionsResponse], + request: tool.ListToolVersionsRequest, + response: tool.ListToolVersionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = tool.ListToolVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tool.ListToolVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[tool.ToolVersion]: + for page in self.pages: + yield from page.tool_versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolVersionsAsyncPager: + """A pager for iterating through ``list_tool_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tool_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListToolVersions`` requests and continue to iterate + through the ``tool_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse` + attributes are available on the 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[tool.ListToolVersionsResponse]], + request: tool.ListToolVersionsRequest, + response: tool.ListToolVersionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListToolVersionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = tool.ListToolVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tool.ListToolVersionsResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[tool.ToolVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.tool_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/README.rst b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/README.rst new file mode 100644 index 000000000000..f7b77e1167bf --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ToolsTransport` is the ABC for all transports. +- public child `ToolsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ToolsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseToolsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ToolsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/__init__.py new file mode 100644 index 000000000000..6cd24e40959c --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 ToolsTransport +from .grpc import ToolsGrpcTransport +from .grpc_asyncio import ToolsGrpcAsyncIOTransport +from .rest import ToolsRestInterceptor, ToolsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ToolsTransport]] +_transport_registry["grpc"] = ToolsGrpcTransport +_transport_registry["grpc_asyncio"] = ToolsGrpcAsyncIOTransport +_transport_registry["rest"] = ToolsRestTransport + +__all__ = ( + "ToolsTransport", + "ToolsGrpcTransport", + "ToolsGrpcAsyncIOTransport", + "ToolsRestTransport", + "ToolsRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/base.py new file mode 100644 index 000000000000..888124168f07 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/base.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3 import gapic_version as package_version +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ToolsTransport(abc.ABC): + """Abstract transport class for Tools.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_tool: gapic_v1.method.wrap_method( + self.create_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_tools: gapic_v1.method.wrap_method( + self.list_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_tool: gapic_v1.method.wrap_method( + self.get_tool, + default_timeout=None, + client_info=client_info, + ), + self.update_tool: gapic_v1.method.wrap_method( + self.update_tool, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool: gapic_v1.method.wrap_method( + self.delete_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_tool_versions: gapic_v1.method.wrap_method( + self.list_tool_versions, + default_timeout=None, + client_info=client_info, + ), + self.create_tool_version: gapic_v1.method.wrap_method( + self.create_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.get_tool_version: gapic_v1.method.wrap_method( + self.get_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool_version: gapic_v1.method.wrap_method( + self.delete_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_tool_version: gapic_v1.method.wrap_method( + self.restore_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_tool( + self, + ) -> Callable[ + [gcdc_tool.CreateToolRequest], Union[gcdc_tool.Tool, Awaitable[gcdc_tool.Tool]] + ]: + raise NotImplementedError() + + @property + def list_tools( + self, + ) -> Callable[ + [tool.ListToolsRequest], + Union[tool.ListToolsResponse, Awaitable[tool.ListToolsResponse]], + ]: + raise NotImplementedError() + + @property + def get_tool( + self, + ) -> Callable[[tool.GetToolRequest], Union[tool.Tool, Awaitable[tool.Tool]]]: + raise NotImplementedError() + + @property + def update_tool( + self, + ) -> Callable[ + [gcdc_tool.UpdateToolRequest], Union[gcdc_tool.Tool, Awaitable[gcdc_tool.Tool]] + ]: + raise NotImplementedError() + + @property + def delete_tool( + self, + ) -> Callable[ + [tool.DeleteToolRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def list_tool_versions( + self, + ) -> Callable[ + [tool.ListToolVersionsRequest], + Union[tool.ListToolVersionsResponse, Awaitable[tool.ListToolVersionsResponse]], + ]: + raise NotImplementedError() + + @property + def create_tool_version( + self, + ) -> Callable[ + [tool.CreateToolVersionRequest], + Union[tool.ToolVersion, Awaitable[tool.ToolVersion]], + ]: + raise NotImplementedError() + + @property + def get_tool_version( + self, + ) -> Callable[ + [tool.GetToolVersionRequest], + Union[tool.ToolVersion, Awaitable[tool.ToolVersion]], + ]: + raise NotImplementedError() + + @property + def delete_tool_version( + self, + ) -> Callable[ + [tool.DeleteToolVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def restore_tool_version( + self, + ) -> Callable[ + [tool.RestoreToolVersionRequest], + Union[ + tool.RestoreToolVersionResponse, Awaitable[tool.RestoreToolVersionResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ToolsTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc.py new file mode 100644 index 000000000000..cc3deb60aac5 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc.py @@ -0,0 +1,684 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolsGrpcTransport(ToolsTransport): + """gRPC backend transport for Tools. + + Service for managing [Tools][google.cloud.dialogflow.cx.v3.Tool]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_tool(self) -> Callable[[gcdc_tool.CreateToolRequest], gcdc_tool.Tool]: + r"""Return a callable for the create tool method over gRPC. + + Creates a [Tool][google.cloud.dialogflow.cx.v3.Tool] in the + specified agent. + + Returns: + Callable[[~.CreateToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool" not in self._stubs: + self._stubs["create_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/CreateTool", + request_serializer=gcdc_tool.CreateToolRequest.serialize, + response_deserializer=gcdc_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def list_tools(self) -> Callable[[tool.ListToolsRequest], tool.ListToolsResponse]: + r"""Return a callable for the list tools method over gRPC. + + Returns a list of [Tools][google.cloud.dialogflow.cx.v3.Tool] in + the specified agent. + + Returns: + Callable[[~.ListToolsRequest], + ~.ListToolsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tools" not in self._stubs: + self._stubs["list_tools"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/ListTools", + request_serializer=tool.ListToolsRequest.serialize, + response_deserializer=tool.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def get_tool(self) -> Callable[[tool.GetToolRequest], tool.Tool]: + r"""Return a callable for the get tool method over gRPC. + + Retrieves the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.GetToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool" not in self._stubs: + self._stubs["get_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/GetTool", + request_serializer=tool.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def update_tool(self) -> Callable[[gcdc_tool.UpdateToolRequest], gcdc_tool.Tool]: + r"""Return a callable for the update tool method over gRPC. + + Update the specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.UpdateToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool" not in self._stubs: + self._stubs["update_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/UpdateTool", + request_serializer=gcdc_tool.UpdateToolRequest.serialize, + response_deserializer=gcdc_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + @property + def delete_tool(self) -> Callable[[tool.DeleteToolRequest], empty_pb2.Empty]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes a specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.DeleteToolRequest], + ~.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_tool" not in self._stubs: + self._stubs["delete_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/DeleteTool", + request_serializer=tool.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def list_tool_versions( + self, + ) -> Callable[[tool.ListToolVersionsRequest], tool.ListToolVersionsResponse]: + r"""Return a callable for the list tool versions method over gRPC. + + List versions of the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.ListToolVersionsRequest], + ~.ListToolVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tool_versions" not in self._stubs: + self._stubs["list_tool_versions"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/ListToolVersions", + request_serializer=tool.ListToolVersionsRequest.serialize, + response_deserializer=tool.ListToolVersionsResponse.deserialize, + ) + return self._stubs["list_tool_versions"] + + @property + def create_tool_version( + self, + ) -> Callable[[tool.CreateToolVersionRequest], tool.ToolVersion]: + r"""Return a callable for the create tool version method over gRPC. + + Creates a version for the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.CreateToolVersionRequest], + ~.ToolVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool_version" not in self._stubs: + self._stubs["create_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/CreateToolVersion", + request_serializer=tool.CreateToolVersionRequest.serialize, + response_deserializer=tool.ToolVersion.deserialize, + ) + return self._stubs["create_tool_version"] + + @property + def get_tool_version( + self, + ) -> Callable[[tool.GetToolVersionRequest], tool.ToolVersion]: + r"""Return a callable for the get tool version method over gRPC. + + Retrieves the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.GetToolVersionRequest], + ~.ToolVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool_version" not in self._stubs: + self._stubs["get_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/GetToolVersion", + request_serializer=tool.GetToolVersionRequest.serialize, + response_deserializer=tool.ToolVersion.deserialize, + ) + return self._stubs["get_tool_version"] + + @property + def delete_tool_version( + self, + ) -> Callable[[tool.DeleteToolVersionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete tool version method over gRPC. + + Deletes the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.DeleteToolVersionRequest], + ~.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_tool_version" not in self._stubs: + self._stubs["delete_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/DeleteToolVersion", + request_serializer=tool.DeleteToolVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool_version"] + + @property + def restore_tool_version( + self, + ) -> Callable[[tool.RestoreToolVersionRequest], tool.RestoreToolVersionResponse]: + r"""Return a callable for the restore tool version method over gRPC. + + Retrieves the specified version of the Tool and + stores it as the current tool draft, returning the tool + with resources updated. + + Returns: + Callable[[~.RestoreToolVersionRequest], + ~.RestoreToolVersionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool_version" not in self._stubs: + self._stubs["restore_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/RestoreToolVersion", + request_serializer=tool.RestoreToolVersionRequest.serialize, + response_deserializer=tool.RestoreToolVersionResponse.deserialize, + ) + return self._stubs["restore_tool_version"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ToolsGrpcTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1b2bb781523f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/grpc_asyncio.py @@ -0,0 +1,789 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport +from .grpc import ToolsGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolsGrpcAsyncIOTransport(ToolsTransport): + """gRPC AsyncIO backend transport for Tools. + + Service for managing [Tools][google.cloud.dialogflow.cx.v3.Tool]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_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_tool( + self, + ) -> Callable[[gcdc_tool.CreateToolRequest], Awaitable[gcdc_tool.Tool]]: + r"""Return a callable for the create tool method over gRPC. + + Creates a [Tool][google.cloud.dialogflow.cx.v3.Tool] in the + specified agent. + + Returns: + Callable[[~.CreateToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool" not in self._stubs: + self._stubs["create_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/CreateTool", + request_serializer=gcdc_tool.CreateToolRequest.serialize, + response_deserializer=gcdc_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def list_tools( + self, + ) -> Callable[[tool.ListToolsRequest], Awaitable[tool.ListToolsResponse]]: + r"""Return a callable for the list tools method over gRPC. + + Returns a list of [Tools][google.cloud.dialogflow.cx.v3.Tool] in + the specified agent. + + Returns: + Callable[[~.ListToolsRequest], + Awaitable[~.ListToolsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tools" not in self._stubs: + self._stubs["list_tools"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/ListTools", + request_serializer=tool.ListToolsRequest.serialize, + response_deserializer=tool.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def get_tool(self) -> Callable[[tool.GetToolRequest], Awaitable[tool.Tool]]: + r"""Return a callable for the get tool method over gRPC. + + Retrieves the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.GetToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool" not in self._stubs: + self._stubs["get_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/GetTool", + request_serializer=tool.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def update_tool( + self, + ) -> Callable[[gcdc_tool.UpdateToolRequest], Awaitable[gcdc_tool.Tool]]: + r"""Return a callable for the update tool method over gRPC. + + Update the specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.UpdateToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool" not in self._stubs: + self._stubs["update_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/UpdateTool", + request_serializer=gcdc_tool.UpdateToolRequest.serialize, + response_deserializer=gcdc_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + @property + def delete_tool( + self, + ) -> Callable[[tool.DeleteToolRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes a specified [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.DeleteToolRequest], + 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_tool" not in self._stubs: + self._stubs["delete_tool"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/DeleteTool", + request_serializer=tool.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def list_tool_versions( + self, + ) -> Callable[ + [tool.ListToolVersionsRequest], Awaitable[tool.ListToolVersionsResponse] + ]: + r"""Return a callable for the list tool versions method over gRPC. + + List versions of the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.ListToolVersionsRequest], + Awaitable[~.ListToolVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tool_versions" not in self._stubs: + self._stubs["list_tool_versions"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/ListToolVersions", + request_serializer=tool.ListToolVersionsRequest.serialize, + response_deserializer=tool.ListToolVersionsResponse.deserialize, + ) + return self._stubs["list_tool_versions"] + + @property + def create_tool_version( + self, + ) -> Callable[[tool.CreateToolVersionRequest], Awaitable[tool.ToolVersion]]: + r"""Return a callable for the create tool version method over gRPC. + + Creates a version for the specified + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.CreateToolVersionRequest], + Awaitable[~.ToolVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool_version" not in self._stubs: + self._stubs["create_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/CreateToolVersion", + request_serializer=tool.CreateToolVersionRequest.serialize, + response_deserializer=tool.ToolVersion.deserialize, + ) + return self._stubs["create_tool_version"] + + @property + def get_tool_version( + self, + ) -> Callable[[tool.GetToolVersionRequest], Awaitable[tool.ToolVersion]]: + r"""Return a callable for the get tool version method over gRPC. + + Retrieves the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.GetToolVersionRequest], + Awaitable[~.ToolVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool_version" not in self._stubs: + self._stubs["get_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/GetToolVersion", + request_serializer=tool.GetToolVersionRequest.serialize, + response_deserializer=tool.ToolVersion.deserialize, + ) + return self._stubs["get_tool_version"] + + @property + def delete_tool_version( + self, + ) -> Callable[[tool.DeleteToolVersionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tool version method over gRPC. + + Deletes the specified version of the + [Tool][google.cloud.dialogflow.cx.v3.Tool]. + + Returns: + Callable[[~.DeleteToolVersionRequest], + 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_tool_version" not in self._stubs: + self._stubs["delete_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/DeleteToolVersion", + request_serializer=tool.DeleteToolVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool_version"] + + @property + def restore_tool_version( + self, + ) -> Callable[ + [tool.RestoreToolVersionRequest], Awaitable[tool.RestoreToolVersionResponse] + ]: + r"""Return a callable for the restore tool version method over gRPC. + + Retrieves the specified version of the Tool and + stores it as the current tool draft, returning the tool + with resources updated. + + Returns: + Callable[[~.RestoreToolVersionRequest], + Awaitable[~.RestoreToolVersionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tool_version" not in self._stubs: + self._stubs["restore_tool_version"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Tools/RestoreToolVersion", + request_serializer=tool.RestoreToolVersionRequest.serialize, + response_deserializer=tool.RestoreToolVersionResponse.deserialize, + ) + return self._stubs["restore_tool_version"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_tool: self._wrap_method( + self.create_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_tools: self._wrap_method( + self.list_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_tool: self._wrap_method( + self.get_tool, + default_timeout=None, + client_info=client_info, + ), + self.update_tool: self._wrap_method( + self.update_tool, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool: self._wrap_method( + self.delete_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_tool_versions: self._wrap_method( + self.list_tool_versions, + default_timeout=None, + client_info=client_info, + ), + self.create_tool_version: self._wrap_method( + self.create_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.get_tool_version: self._wrap_method( + self.get_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool_version: self._wrap_method( + self.delete_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_tool_version: self._wrap_method( + self.restore_tool_version, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("ToolsGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest.py new file mode 100644 index 000000000000..8fdbcdd02d30 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest.py @@ -0,0 +1,2963 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseToolsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ToolsRestInterceptor: + """Interceptor for Tools. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ToolsRestTransport. + + .. code-block:: python + class MyCustomToolsInterceptor(ToolsRestInterceptor): + def pre_create_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tool_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tool_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_tool_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tool_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tool_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tool_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tool_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_tool_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_tool_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tool(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ToolsRestTransport(interceptor=MyCustomToolsInterceptor()) + client = ToolsClient(transport=transport) + + + """ + + def pre_create_tool( + self, + request: gcdc_tool.CreateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_tool.CreateToolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_create_tool(self, response: gcdc_tool.Tool) -> gcdc_tool.Tool: + """Post-rpc interceptor for create_tool + + DEPRECATED. Please use the `post_create_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_create_tool` interceptor runs + before the `post_create_tool_with_metadata` interceptor. + """ + return response + + def post_create_tool_with_metadata( + self, + response: gcdc_tool.Tool, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_create_tool_with_metadata` + interceptor in new development instead of the `post_create_tool` interceptor. + When both interceptors are used, this `post_create_tool_with_metadata` interceptor runs after the + `post_create_tool` interceptor. The (possibly modified) response returned by + `post_create_tool` will be passed to + `post_create_tool_with_metadata`. + """ + return response, metadata + + def pre_create_tool_version( + self, + request: tool.CreateToolVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.CreateToolVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_tool_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_create_tool_version(self, response: tool.ToolVersion) -> tool.ToolVersion: + """Post-rpc interceptor for create_tool_version + + DEPRECATED. Please use the `post_create_tool_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_create_tool_version` interceptor runs + before the `post_create_tool_version_with_metadata` interceptor. + """ + return response + + def post_create_tool_version_with_metadata( + self, + response: tool.ToolVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ToolVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_tool_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_create_tool_version_with_metadata` + interceptor in new development instead of the `post_create_tool_version` interceptor. + When both interceptors are used, this `post_create_tool_version_with_metadata` interceptor runs after the + `post_create_tool_version` interceptor. The (possibly modified) response returned by + `post_create_tool_version` will be passed to + `post_create_tool_version_with_metadata`. + """ + return response, metadata + + def pre_delete_tool( + self, + request: tool.DeleteToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.DeleteToolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def pre_delete_tool_version( + self, + request: tool.DeleteToolVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.DeleteToolVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_tool_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def pre_get_tool( + self, + request: tool.GetToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.GetToolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_get_tool(self, response: tool.Tool) -> tool.Tool: + """Post-rpc interceptor for get_tool + + DEPRECATED. Please use the `post_get_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_get_tool` interceptor runs + before the `post_get_tool_with_metadata` interceptor. + """ + return response + + def post_get_tool_with_metadata( + self, response: tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_get_tool_with_metadata` + interceptor in new development instead of the `post_get_tool` interceptor. + When both interceptors are used, this `post_get_tool_with_metadata` interceptor runs after the + `post_get_tool` interceptor. The (possibly modified) response returned by + `post_get_tool` will be passed to + `post_get_tool_with_metadata`. + """ + return response, metadata + + def pre_get_tool_version( + self, + request: tool.GetToolVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.GetToolVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_tool_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_get_tool_version(self, response: tool.ToolVersion) -> tool.ToolVersion: + """Post-rpc interceptor for get_tool_version + + DEPRECATED. Please use the `post_get_tool_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_get_tool_version` interceptor runs + before the `post_get_tool_version_with_metadata` interceptor. + """ + return response + + def post_get_tool_version_with_metadata( + self, + response: tool.ToolVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ToolVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_tool_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_get_tool_version_with_metadata` + interceptor in new development instead of the `post_get_tool_version` interceptor. + When both interceptors are used, this `post_get_tool_version_with_metadata` interceptor runs after the + `post_get_tool_version` interceptor. The (possibly modified) response returned by + `post_get_tool_version` will be passed to + `post_get_tool_version_with_metadata`. + """ + return response, metadata + + def pre_list_tools( + self, + request: tool.ListToolsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ListToolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_tools + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_list_tools( + self, response: tool.ListToolsResponse + ) -> tool.ListToolsResponse: + """Post-rpc interceptor for list_tools + + DEPRECATED. Please use the `post_list_tools_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_list_tools` interceptor runs + before the `post_list_tools_with_metadata` interceptor. + """ + return response + + def post_list_tools_with_metadata( + self, + response: tool.ListToolsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ListToolsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_tools + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_list_tools_with_metadata` + interceptor in new development instead of the `post_list_tools` interceptor. + When both interceptors are used, this `post_list_tools_with_metadata` interceptor runs after the + `post_list_tools` interceptor. The (possibly modified) response returned by + `post_list_tools` will be passed to + `post_list_tools_with_metadata`. + """ + return response, metadata + + def pre_list_tool_versions( + self, + request: tool.ListToolVersionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ListToolVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_tool_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_list_tool_versions( + self, response: tool.ListToolVersionsResponse + ) -> tool.ListToolVersionsResponse: + """Post-rpc interceptor for list_tool_versions + + DEPRECATED. Please use the `post_list_tool_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_list_tool_versions` interceptor runs + before the `post_list_tool_versions_with_metadata` interceptor. + """ + return response + + def post_list_tool_versions_with_metadata( + self, + response: tool.ListToolVersionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.ListToolVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_tool_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_list_tool_versions_with_metadata` + interceptor in new development instead of the `post_list_tool_versions` interceptor. + When both interceptors are used, this `post_list_tool_versions_with_metadata` interceptor runs after the + `post_list_tool_versions` interceptor. The (possibly modified) response returned by + `post_list_tool_versions` will be passed to + `post_list_tool_versions_with_metadata`. + """ + return response, metadata + + def pre_restore_tool_version( + self, + request: tool.RestoreToolVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.RestoreToolVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for restore_tool_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_restore_tool_version( + self, response: tool.RestoreToolVersionResponse + ) -> tool.RestoreToolVersionResponse: + """Post-rpc interceptor for restore_tool_version + + DEPRECATED. Please use the `post_restore_tool_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_restore_tool_version` interceptor runs + before the `post_restore_tool_version_with_metadata` interceptor. + """ + return response + + def post_restore_tool_version_with_metadata( + self, + response: tool.RestoreToolVersionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool.RestoreToolVersionResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for restore_tool_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_restore_tool_version_with_metadata` + interceptor in new development instead of the `post_restore_tool_version` interceptor. + When both interceptors are used, this `post_restore_tool_version_with_metadata` interceptor runs after the + `post_restore_tool_version` interceptor. The (possibly modified) response returned by + `post_restore_tool_version` will be passed to + `post_restore_tool_version_with_metadata`. + """ + return response, metadata + + def pre_update_tool( + self, + request: gcdc_tool.UpdateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_tool.UpdateToolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_update_tool(self, response: gcdc_tool.Tool) -> gcdc_tool.Tool: + """Post-rpc interceptor for update_tool + + DEPRECATED. Please use the `post_update_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Tools server but before + it is returned to user code. This `post_update_tool` interceptor runs + before the `post_update_tool_with_metadata` interceptor. + """ + return response + + def post_update_tool_with_metadata( + self, + response: gcdc_tool.Tool, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcdc_tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Tools server but before it is returned to user code. + + We recommend only using this `post_update_tool_with_metadata` + interceptor in new development instead of the `post_update_tool` interceptor. + When both interceptors are used, this `post_update_tool_with_metadata` interceptor runs after the + `post_update_tool` interceptor. The (possibly modified) response returned by + `post_update_tool` will be passed to + `post_update_tool_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Tools server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Tools server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Tools server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Tools server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Tools server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Tools server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ToolsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ToolsRestInterceptor + + +class ToolsRestTransport(_BaseToolsRestTransport): + """REST backend synchronous transport for Tools. + + Service for managing [Tools][google.cloud.dialogflow.cx.v3.Tool]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ToolsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ToolsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateTool(_BaseToolsRestTransport._BaseCreateTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.CreateTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_tool.CreateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Call the create tool method over HTTP. + + Args: + request (~.gcdc_tool.CreateToolRequest): + The request object. The request message for + [Tools.CreateTool][google.cloud.dialogflow.cx.v3.Tools.CreateTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_tool.Tool: + A tool provides a list of actions which are available to + the [Playbook][google.cloud.dialogflow.cx.v3.Playbook] + to attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool which + contains the schema and authentication information. + + """ + + http_options = _BaseToolsRestTransport._BaseCreateTool._get_http_options() + + request, metadata = self._interceptor.pre_create_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseCreateTool._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseToolsRestTransport._BaseCreateTool._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseCreateTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.CreateTool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "CreateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._CreateTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_tool.Tool() + pb_resp = gcdc_tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.create_tool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "CreateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateToolVersion( + _BaseToolsRestTransport._BaseCreateToolVersion, ToolsRestStub + ): + def __hash__(self): + return hash("ToolsRestTransport.CreateToolVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tool.CreateToolVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Call the create tool version method over HTTP. + + Args: + request (~.tool.CreateToolVersionRequest): + The request object. The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + + http_options = ( + _BaseToolsRestTransport._BaseCreateToolVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_tool_version( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseCreateToolVersion._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseToolsRestTransport._BaseCreateToolVersion._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseCreateToolVersion._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.CreateToolVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "CreateToolVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._CreateToolVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.ToolVersion() + pb_resp = tool.ToolVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_tool_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_tool_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.ToolVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.create_tool_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "CreateToolVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteTool(_BaseToolsRestTransport._BaseDeleteTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.DeleteTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.DeleteToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete tool method over HTTP. + + Args: + request (~.tool.DeleteToolRequest): + The request object. The request message for + [Tools.DeleteTool][google.cloud.dialogflow.cx.v3.Tools.DeleteTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseToolsRestTransport._BaseDeleteTool._get_http_options() + + request, metadata = self._interceptor.pre_delete_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseDeleteTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseDeleteTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.DeleteTool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "DeleteTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._DeleteTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteToolVersion( + _BaseToolsRestTransport._BaseDeleteToolVersion, ToolsRestStub + ): + def __hash__(self): + return hash("ToolsRestTransport.DeleteToolVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.DeleteToolVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete tool version method over HTTP. + + Args: + request (~.tool.DeleteToolVersionRequest): + The request object. The request message for + [Tools.DeleteToolVersion][google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseToolsRestTransport._BaseDeleteToolVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_tool_version( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseDeleteToolVersion._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseDeleteToolVersion._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.DeleteToolVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "DeleteToolVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._DeleteToolVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetTool(_BaseToolsRestTransport._BaseGetTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.GetTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.GetToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Call the get tool method over HTTP. + + Args: + request (~.tool.GetToolRequest): + The request object. The request message for + [Tools.GetTool][google.cloud.dialogflow.cx.v3.Tools.GetTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.Tool: + A tool provides a list of actions which are available to + the [Playbook][google.cloud.dialogflow.cx.v3.Playbook] + to attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool which + contains the schema and authentication information. + + """ + + http_options = _BaseToolsRestTransport._BaseGetTool._get_http_options() + + request, metadata = self._interceptor.pre_get_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseToolsRestTransport._BaseGetTool._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.GetTool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._GetTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.Tool() + pb_resp = tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.get_tool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetToolVersion(_BaseToolsRestTransport._BaseGetToolVersion, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.GetToolVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.GetToolVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ToolVersion: + r"""Call the get tool version method over HTTP. + + Args: + request (~.tool.GetToolVersionRequest): + The request object. The request message for + [Tools.GetToolVersion][google.cloud.dialogflow.cx.v3.Tools.GetToolVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.ToolVersion: + Tool version is a snapshot of the + tool at certain timestamp. + + """ + + http_options = ( + _BaseToolsRestTransport._BaseGetToolVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_tool_version( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetToolVersion._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseGetToolVersion._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.GetToolVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetToolVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._GetToolVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.ToolVersion() + pb_resp = tool.ToolVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_tool_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_tool_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.ToolVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.get_tool_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetToolVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTools(_BaseToolsRestTransport._BaseListTools, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.ListTools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.ListToolsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ListToolsResponse: + r"""Call the list tools method over HTTP. + + Args: + request (~.tool.ListToolsRequest): + The request object. The request message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.ListToolsResponse: + The response message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + + """ + + http_options = _BaseToolsRestTransport._BaseListTools._get_http_options() + + request, metadata = self._interceptor.pre_list_tools(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListTools._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseListTools._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.ListTools", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListTools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._ListTools._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.ListToolsResponse() + pb_resp = tool.ListToolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_tools(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_tools_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.ListToolsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.list_tools", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListTools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListToolVersions( + _BaseToolsRestTransport._BaseListToolVersions, ToolsRestStub + ): + def __hash__(self): + return hash("ToolsRestTransport.ListToolVersions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: tool.ListToolVersionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ListToolVersionsResponse: + r"""Call the list tool versions method over HTTP. + + Args: + request (~.tool.ListToolVersionsRequest): + The request object. The request message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.ListToolVersionsResponse: + The response message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + + """ + + http_options = ( + _BaseToolsRestTransport._BaseListToolVersions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_tool_versions( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseListToolVersions._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseListToolVersions._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.ListToolVersions", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListToolVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._ListToolVersions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.ListToolVersionsResponse() + pb_resp = tool.ListToolVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_tool_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_tool_versions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.ListToolVersionsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.list_tool_versions", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListToolVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RestoreToolVersion( + _BaseToolsRestTransport._BaseRestoreToolVersion, ToolsRestStub + ): + def __hash__(self): + return hash("ToolsRestTransport.RestoreToolVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tool.RestoreToolVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.RestoreToolVersionResponse: + r"""Call the restore tool version method over HTTP. + + Args: + request (~.tool.RestoreToolVersionRequest): + The request object. The request message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.RestoreToolVersionResponse: + The response message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + + """ + + http_options = ( + _BaseToolsRestTransport._BaseRestoreToolVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_restore_tool_version( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseRestoreToolVersion._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseToolsRestTransport._BaseRestoreToolVersion._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseRestoreToolVersion._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.RestoreToolVersion", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "RestoreToolVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._RestoreToolVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.RestoreToolVersionResponse() + pb_resp = tool.RestoreToolVersionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_restore_tool_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restore_tool_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.RestoreToolVersionResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.restore_tool_version", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "RestoreToolVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateTool(_BaseToolsRestTransport._BaseUpdateTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.UpdateTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcdc_tool.UpdateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcdc_tool.Tool: + r"""Call the update tool method over HTTP. + + Args: + request (~.gcdc_tool.UpdateToolRequest): + The request object. The request message for + [Tools.UpdateTool][google.cloud.dialogflow.cx.v3.Tools.UpdateTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcdc_tool.Tool: + A tool provides a list of actions which are available to + the [Playbook][google.cloud.dialogflow.cx.v3.Playbook] + to attain its goal. A Tool consists of a description of + the tool's usage and a specification of the tool which + contains the schema and authentication information. + + """ + + http_options = _BaseToolsRestTransport._BaseUpdateTool._get_http_options() + + request, metadata = self._interceptor.pre_update_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseUpdateTool._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseToolsRestTransport._BaseUpdateTool._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseUpdateTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.UpdateTool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "UpdateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._UpdateTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcdc_tool.Tool() + pb_resp = gcdc_tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcdc_tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsClient.update_tool", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "UpdateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_tool(self) -> Callable[[gcdc_tool.CreateToolRequest], gcdc_tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tool_version( + self, + ) -> Callable[[tool.CreateToolVersionRequest], tool.ToolVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateToolVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tool(self) -> Callable[[tool.DeleteToolRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tool_version( + self, + ) -> Callable[[tool.DeleteToolVersionRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteToolVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tool(self) -> Callable[[tool.GetToolRequest], tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tool_version( + self, + ) -> Callable[[tool.GetToolVersionRequest], tool.ToolVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetToolVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tools(self) -> Callable[[tool.ListToolsRequest], tool.ListToolsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTools(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tool_versions( + self, + ) -> Callable[[tool.ListToolVersionsRequest], tool.ListToolVersionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListToolVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_tool_version( + self, + ) -> Callable[[tool.RestoreToolVersionRequest], tool.RestoreToolVersionResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreToolVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tool(self) -> Callable[[gcdc_tool.UpdateToolRequest], gcdc_tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseToolsRestTransport._BaseGetLocation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseToolsRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseToolsRestTransport._BaseListLocations, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseToolsRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseToolsRestTransport._BaseCancelOperation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseToolsRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseToolsRestTransport._BaseGetOperation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseToolsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseToolsRestTransport._BaseListOperations, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseToolsRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.dialogflow.cx_v3.ToolsClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.dialogflow.cx_v3.ToolsAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.cx.v3.Tools", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ToolsRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest_base.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest_base.py new file mode 100644 index 000000000000..5202607205a6 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/tools/transports/rest_base.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport + + +class _BaseToolsRestTransport(ToolsTransport): + """Base REST backend transport for Tools. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*}/tools", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_tool.CreateToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseCreateTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateToolVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/tools/*}/versions", + "body": "tool_version", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.CreateToolVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseCreateToolVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/agents/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.DeleteToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseDeleteTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteToolVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.DeleteToolVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseDeleteToolVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.GetToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseGetTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetToolVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.GetToolVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseGetToolVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*/agents/*}/tools", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.ListToolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseListTools._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListToolVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=projects/*/locations/*/agents/*/tools/*}/versions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.ListToolVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseListToolVersions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestoreToolVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}:restore", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.RestoreToolVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseRestoreToolVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{tool.name=projects/*/locations/*/agents/*/tools/*}", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcdc_tool.UpdateToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolsRestTransport._BaseUpdateTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v3/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v3/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseToolsRestTransport",) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py index 8910b41121db..f2da7995d9d5 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py @@ -93,6 +93,8 @@ class TransitionRouteGroupsAsyncClient: parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) page_path = staticmethod(TransitionRouteGroupsClient.page_path) parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) + tool_path = staticmethod(TransitionRouteGroupsClient.tool_path) + parse_tool_path = staticmethod(TransitionRouteGroupsClient.parse_tool_path) transition_route_group_path = staticmethod( TransitionRouteGroupsClient.transition_route_group_path ) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py index 36d54f296cef..69733d58148f 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py @@ -332,6 +332,30 @@ def parse_page_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + agent: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def transition_route_group_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py index 933710bcb3a8..4185ae645445 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py @@ -81,6 +81,8 @@ class WebhooksAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = WebhooksClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = WebhooksClient._DEFAULT_UNIVERSE + secret_version_path = staticmethod(WebhooksClient.secret_version_path) + parse_secret_version_path = staticmethod(WebhooksClient.parse_secret_version_path) service_path = staticmethod(WebhooksClient.service_path) parse_service_path = staticmethod(WebhooksClient.parse_service_path) webhook_path = staticmethod(WebhooksClient.webhook_path) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/client.py index 53197e30db24..47aae694554c 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/client.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/services/webhooks/client.py @@ -230,6 +230,28 @@ def transport(self) -> WebhooksTransport: """ return self._transport + @staticmethod + def secret_version_path( + project: str, + secret: str, + version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_path( project: str, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py index 5ab5e4ba03fa..a13971240d2e 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/__init__.py @@ -51,6 +51,7 @@ ListChangelogsRequest, ListChangelogsResponse, ) +from .code_block import CodeBlock from .data_store_connection import ( DataStoreConnection, DataStoreConnectionSignals, @@ -98,6 +99,15 @@ RunContinuousTestResponse, UpdateEnvironmentRequest, ) +from .example import ( + CreateExampleRequest, + DeleteExampleRequest, + Example, + GetExampleRequest, + ListExamplesRequest, + ListExamplesResponse, + UpdateExampleRequest, +) from .experiment import ( CreateExperimentRequest, DeleteExperimentRequest, @@ -134,7 +144,7 @@ ) from .fulfillment import Fulfillment from .gcs import GcsDestination -from .generative_settings import GenerativeSettings +from .generative_settings import GenerativeSettings, LlmModelSettings from .generator import ( CreateGeneratorRequest, DeleteGeneratorRequest, @@ -176,6 +186,35 @@ TransitionRoute, UpdatePageRequest, ) +from .parameter_definition import ( + DataType, + InlineSchema, + ParameterDefinition, + TypeSchema, +) +from .playbook import ( + CreatePlaybookRequest, + CreatePlaybookVersionRequest, + DeletePlaybookRequest, + DeletePlaybookVersionRequest, + ExportPlaybookRequest, + ExportPlaybookResponse, + GetPlaybookRequest, + GetPlaybookVersionRequest, + Handler, + ImportPlaybookRequest, + ImportPlaybookResponse, + ListPlaybooksRequest, + ListPlaybooksResponse, + ListPlaybookVersionsRequest, + ListPlaybookVersionsResponse, + Playbook, + PlaybookImportStrategy, + PlaybookVersion, + RestorePlaybookVersionRequest, + RestorePlaybookVersionResponse, + UpdatePlaybookRequest, +) from .response_message import ResponseMessage from .safety_settings import SafetySettings from .security_settings import ( @@ -195,6 +234,7 @@ CloudConversationDebuggingInfo, DetectIntentRequest, DetectIntentResponse, + DetectIntentResponseView, DtmfInput, EventInput, FilterSpecs, @@ -260,6 +300,37 @@ TransitionRouteGroupCoverage, UpdateTestCaseRequest, ) +from .tool import ( + CreateToolRequest, + CreateToolVersionRequest, + DeleteToolRequest, + DeleteToolVersionRequest, + GetToolRequest, + GetToolVersionRequest, + ListToolsRequest, + ListToolsResponse, + ListToolVersionsRequest, + ListToolVersionsResponse, + RestoreToolVersionRequest, + RestoreToolVersionResponse, + Tool, + ToolVersion, + UpdateToolRequest, +) +from .tool_call import ToolCall, ToolCallResult +from .trace import ( + Action, + AgentUtterance, + FlowInvocation, + FlowTransition, + OutputState, + PlaybookInput, + PlaybookInvocation, + PlaybookOutput, + PlaybookTransition, + ToolUse, + UserUtterance, +) from .transition_route_group import ( CreateTransitionRouteGroupRequest, DeleteTransitionRouteGroupRequest, @@ -331,6 +402,7 @@ "GetChangelogRequest", "ListChangelogsRequest", "ListChangelogsResponse", + "CodeBlock", "DataStoreConnection", "DataStoreConnectionSignals", "DataStoreType", @@ -370,6 +442,13 @@ "RunContinuousTestRequest", "RunContinuousTestResponse", "UpdateEnvironmentRequest", + "CreateExampleRequest", + "DeleteExampleRequest", + "Example", + "GetExampleRequest", + "ListExamplesRequest", + "ListExamplesResponse", + "UpdateExampleRequest", "CreateExperimentRequest", "DeleteExperimentRequest", "Experiment", @@ -403,6 +482,7 @@ "Fulfillment", "GcsDestination", "GenerativeSettings", + "LlmModelSettings", "CreateGeneratorRequest", "DeleteGeneratorRequest", "Generator", @@ -439,6 +519,31 @@ "Page", "TransitionRoute", "UpdatePageRequest", + "InlineSchema", + "ParameterDefinition", + "TypeSchema", + "DataType", + "CreatePlaybookRequest", + "CreatePlaybookVersionRequest", + "DeletePlaybookRequest", + "DeletePlaybookVersionRequest", + "ExportPlaybookRequest", + "ExportPlaybookResponse", + "GetPlaybookRequest", + "GetPlaybookVersionRequest", + "Handler", + "ImportPlaybookRequest", + "ImportPlaybookResponse", + "ListPlaybooksRequest", + "ListPlaybooksResponse", + "ListPlaybookVersionsRequest", + "ListPlaybookVersionsResponse", + "Playbook", + "PlaybookImportStrategy", + "PlaybookVersion", + "RestorePlaybookVersionRequest", + "RestorePlaybookVersionResponse", + "UpdatePlaybookRequest", "ResponseMessage", "SafetySettings", "CreateSecuritySettingsRequest", @@ -474,6 +579,7 @@ "StreamingRecognitionResult", "SubmitAnswerFeedbackRequest", "TextInput", + "DetectIntentResponseView", "CreateSessionEntityTypeRequest", "DeleteSessionEntityTypeRequest", "GetSessionEntityTypeRequest", @@ -515,6 +621,34 @@ "TransitionRouteGroupCoverage", "UpdateTestCaseRequest", "TestResult", + "CreateToolRequest", + "CreateToolVersionRequest", + "DeleteToolRequest", + "DeleteToolVersionRequest", + "GetToolRequest", + "GetToolVersionRequest", + "ListToolsRequest", + "ListToolsResponse", + "ListToolVersionsRequest", + "ListToolVersionsResponse", + "RestoreToolVersionRequest", + "RestoreToolVersionResponse", + "Tool", + "ToolVersion", + "UpdateToolRequest", + "ToolCall", + "ToolCallResult", + "Action", + "AgentUtterance", + "FlowInvocation", + "FlowTransition", + "PlaybookInput", + "PlaybookInvocation", + "PlaybookOutput", + "PlaybookTransition", + "ToolUse", + "UserUtterance", + "OutputState", "CreateTransitionRouteGroupRequest", "DeleteTransitionRouteGroupRequest", "GetTransitionRouteGroupRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py index 93e4537d98b4..db69fe744b33 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/agent.py @@ -82,6 +82,10 @@ class Agent(proto.Message): [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] and so on to manage the conversation flows. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -123,11 +127,23 @@ class Agent(proto.Message): 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: + 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/``. + Currently only the default start flow with id + "00000000-0000-0000-0000-000000000000" is allowed. + + This field is a member of `oneof`_ ``session_entry_resource``. + start_playbook (str): + Name of the start playbook in this agent. A start playbook + will be automatically created when the agent is created, and + can only be deleted by deleting the agent. Format: + ``projects//locations//agents//playbooks/``. + Currently only the default playbook with id + "00000000-0000-0000-0000-000000000000" is allowed. + + This field is a member of `oneof`_ ``session_entry_resource``. security_settings (str): Name of the [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] @@ -371,6 +387,12 @@ class ClientCertificateSettings(proto.Message): start_flow: str = proto.Field( proto.STRING, number=16, + oneof="session_entry_resource", + ) + start_playbook: str = proto.Field( + proto.STRING, + number=39, + oneof="session_entry_resource", ) security_settings: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/audio_config.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/audio_config.py index 68c2dc9b5721..c931e021d33c 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/audio_config.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/audio_config.py @@ -48,8 +48,8 @@ class AudioEncoding(proto.Enum): AUDIO_ENCODING_UNSPECIFIED (0): Not specified. AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). + Uncompressed 16-bit signed little-endian samples (Linear + PCM). LINT: LEGACY_NAMES AUDIO_ENCODING_FLAC (2): ```FLAC`` `__ (Free Lossless Audio Codec) is the recommended encoding @@ -173,13 +173,13 @@ class OutputAudioEncoding(proto.Enum): OUTPUT_AUDIO_ENCODING_UNSPECIFIED (0): Not specified. OUTPUT_AUDIO_ENCODING_LINEAR_16 (1): - Uncompressed 16-bit signed little-endian - samples (Linear PCM). Audio content returned as - LINEAR16 also contains a WAV header. + Uncompressed 16-bit signed little-endian samples (Linear + PCM). Audio content returned as LINEAR16 also contains a WAV + header. LINT: LEGACY_NAMES OUTPUT_AUDIO_ENCODING_MP3 (2): MP3 audio at 32kbps. OUTPUT_AUDIO_ENCODING_MP3_64_KBPS (4): - MP3 audio at 64kbps. + MP3 audio at 64kbps. LINT: LEGACY_NAMES OUTPUT_AUDIO_ENCODING_OGG_OPUS (3): Opus encoded audio wrapped in an ogg container. The result will be a file which can diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/code_block.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/code_block.py new file mode 100644 index 000000000000..4630fe691d9f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/code_block.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "CodeBlock", + }, +) + + +class CodeBlock(proto.Message): + r"""Represents a code block. + + Attributes: + code (str): + Optional. Source code of the block in Python. + """ + + code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py index 33af80fb9ad1..ad68284144b8 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/data_store_connection.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import struct_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -182,6 +183,8 @@ class SearchSnippet(proto.Message): for the document. text (str): Text included in the prompt. + metadata (google.protobuf.struct_pb2.Struct): + Metadata associated with the document. """ document_title: str = proto.Field( @@ -196,6 +199,11 @@ class SearchSnippet(proto.Message): proto.STRING, number=3, ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) class AnswerGenerationModelCallSignals(proto.Message): r"""Diagnostic info related to the answer generation model call. diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/environment.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/environment.py index 5a86faefacdb..ce908380fbb5 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/environment.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/environment.py @@ -92,13 +92,16 @@ class VersionConfig(proto.Message): Attributes: version (str): - Required. Both flow and playbook versions are - supported. Format for flow version: + Required. Flow, playbook and tool versions + are supported. Format for flow version: projects//locations//agents//flows//versions/. Format for playbook version: projects//locations//agents//playbooks//versions/. + Format for tool version: + + projects//locations//agents//tools//versions/. """ version: str = proto.Field( diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/example.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/example.py new file mode 100644 index 000000000000..bc9b5d91027f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/example.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import trace + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "CreateExampleRequest", + "DeleteExampleRequest", + "ListExamplesRequest", + "ListExamplesResponse", + "GetExampleRequest", + "UpdateExampleRequest", + "Example", + }, +) + + +class CreateExampleRequest(proto.Message): + r"""The request message for + [Examples.CreateExample][google.cloud.dialogflow.cx.v3.Examples.CreateExample]. + + Attributes: + parent (str): + Required. The playbook to create an example for. Format: + ``projects//locations//agents//playbooks/``. + example (google.cloud.dialogflowcx_v3.types.Example): + Required. The example to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + example: "Example" = proto.Field( + proto.MESSAGE, + number=2, + message="Example", + ) + + +class DeleteExampleRequest(proto.Message): + r"""The request message for + [Examples.DeleteExample][google.cloud.dialogflow.cx.v3.Examples.DeleteExample]. + + Attributes: + name (str): + Required. The name of the example to delete. Format: + ``projects//locations//agents//playbooks//examples/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListExamplesRequest(proto.Message): + r"""The request message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + + Attributes: + parent (str): + Required. The playbook to list the examples from. Format: + ``projects//locations//agents//playbooks/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The + [next_page_token][ListExampleResponse.next_page_token] value + returned from a previous list request. + language_code (str): + Optional. The language to list examples for. + If not specified, list all examples under the + playbook. Note: languages must be enabled in the + agent before they can be used. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListExamplesResponse(proto.Message): + r"""The response message for + [Examples.ListExamples][google.cloud.dialogflow.cx.v3.Examples.ListExamples]. + + Attributes: + examples (MutableSequence[google.cloud.dialogflowcx_v3.types.Example]): + The list of examples. There will be a maximum number of + items returned based on the + [page_size][google.cloud.dialogflow.cx.v3.ListExamplesRequest.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 + + examples: MutableSequence["Example"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Example", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetExampleRequest(proto.Message): + r"""The request message for + [Examples.GetExample][google.cloud.dialogflow.cx.v3.Examples.GetExample]. + + Attributes: + name (str): + Required. The name of the example. Format: + ``projects//locations//agents//playbooks//examples/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateExampleRequest(proto.Message): + r"""The request message for + [Examples.UpdateExample][google.cloud.dialogflow.cx.v3.Examples.UpdateExample]. + + Attributes: + example (google.cloud.dialogflowcx_v3.types.Example): + Required. The example to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + example: "Example" = proto.Field( + proto.MESSAGE, + number=1, + message="Example", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Example(proto.Message): + r"""Example represents a sample execution of the playbook in the + conversation. + An example consists of a list of ordered actions performed by + end user or Dialogflow agent according the playbook instructions + to fulfill the task. + + Attributes: + name (str): + The unique identifier of the playbook example. Format: + ``projects//locations//agents//playbooks//examples/``. + playbook_input (google.cloud.dialogflowcx_v3.types.PlaybookInput): + Optional. The input to the playbook in the + example. + playbook_output (google.cloud.dialogflowcx_v3.types.PlaybookOutput): + Optional. The output of the playbook in the + example. + actions (MutableSequence[google.cloud.dialogflowcx_v3.types.Action]): + Required. The ordered list of actions + performed by the end user and the Dialogflow + agent. + display_name (str): + Required. The display name of the example. + description (str): + Optional. The high level concise description + of the example. The max number of characters is + 200. + token_count (int): + Output only. Estimated number of tokes + current example takes when sent to the LLM. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of initial example + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the example was + updated. + conversation_state (google.cloud.dialogflowcx_v3.types.OutputState): + Required. Example's output state. + language_code (str): + Optional. The language code of the example. + If not specified, the agent's default language + is used. Note: languages must be enabled in the + agent before they can be used. Note: example's + language code is not currently used in + dialogflow agents. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + playbook_input: trace.PlaybookInput = proto.Field( + proto.MESSAGE, + number=3, + message=trace.PlaybookInput, + ) + playbook_output: trace.PlaybookOutput = proto.Field( + proto.MESSAGE, + number=4, + message=trace.PlaybookOutput, + ) + actions: MutableSequence[trace.Action] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=trace.Action, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=8, + ) + token_count: int = proto.Field( + proto.INT64, + number=9, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + conversation_state: trace.OutputState = proto.Field( + proto.ENUM, + number=12, + enum=trace.OutputState, + ) + language_code: str = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py index d6c8690729aa..819ac112093b 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/flow.py @@ -21,7 +21,12 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.dialogflowcx_v3.types import import_strategy, page, validation_message +from google.cloud.dialogflowcx_v3.types import ( + import_strategy, + page, + parameter_definition, + validation_message, +) from google.cloud.dialogflowcx_v3.types import ( advanced_settings as gcdc_advanced_settings, ) @@ -211,6 +216,12 @@ class Flow(proto.Message): level. knowledge_connector_settings (google.cloud.dialogflowcx_v3.types.KnowledgeConnectorSettings): Optional. Knowledge connector configuration. + input_parameter_definitions (MutableSequence[google.cloud.dialogflowcx_v3.types.ParameterDefinition]): + Optional. Defined structured input parameters + for this flow. + output_parameter_definitions (MutableSequence[google.cloud.dialogflowcx_v3.types.ParameterDefinition]): + Optional. Defined structured output + parameters for this flow. multi_language_settings (google.cloud.dialogflowcx_v3.types.Flow.MultiLanguageSettings): Optional. Multi-lingual agent settings for this flow. @@ -290,6 +301,20 @@ class MultiLanguageSettings(proto.Message): number=18, message=page.KnowledgeConnectorSettings, ) + input_parameter_definitions: MutableSequence[ + parameter_definition.ParameterDefinition + ] = proto.RepeatedField( + proto.MESSAGE, + number=26, + message=parameter_definition.ParameterDefinition, + ) + output_parameter_definitions: MutableSequence[ + parameter_definition.ParameterDefinition + ] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=parameter_definition.ParameterDefinition, + ) multi_language_settings: MultiLanguageSettings = proto.Field( proto.MESSAGE, number=28, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py index 5993d24d274e..496cd6d464cc 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generative_settings.py @@ -25,6 +25,7 @@ package="google.cloud.dialogflow.cx.v3", manifest={ "GenerativeSettings", + "LlmModelSettings", }, ) @@ -44,6 +45,8 @@ class GenerativeSettings(proto.Message): Settings for knowledge connector. language_code (str): Language for this settings. + llm_model_settings (google.cloud.dialogflowcx_v3.types.LlmModelSettings): + LLM model settings. """ class FallbackSettings(proto.Message): @@ -180,6 +183,31 @@ class KnowledgeConnectorSettings(proto.Message): proto.STRING, number=4, ) + llm_model_settings: "LlmModelSettings" = proto.Field( + proto.MESSAGE, + number=8, + message="LlmModelSettings", + ) + + +class LlmModelSettings(proto.Message): + r"""Settings for LLM models. + + Attributes: + model (str): + The selected LLM model. + prompt_text (str): + The custom prompt to use. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + prompt_text: str = proto.Field( + proto.STRING, + number=2, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generator.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generator.py index a658d6d42283..5a7846c80e70 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generator.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/generator.py @@ -20,6 +20,8 @@ from google.protobuf import field_mask_pb2 # type: ignore import proto # type: ignore +from google.cloud.dialogflowcx_v3.types import generative_settings + __protobuf__ = proto.module( package="google.cloud.dialogflow.cx.v3", manifest={ @@ -61,6 +63,8 @@ class Generator(proto.Message): placeholders (MutableSequence[google.cloud.dialogflowcx_v3.types.Generator.Placeholder]): Optional. List of custom placeholders in the prompt text. + llm_model_settings (google.cloud.dialogflowcx_v3.types.LlmModelSettings): + The LLM model settings. model_parameter (google.cloud.dialogflowcx_v3.types.Generator.ModelParameter): Parameters passed to the LLM to configure its behavior. @@ -161,6 +165,11 @@ class ModelParameter(proto.Message): number=5, message=Placeholder, ) + llm_model_settings: generative_settings.LlmModelSettings = proto.Field( + proto.MESSAGE, + number=9, + message=generative_settings.LlmModelSettings, + ) model_parameter: ModelParameter = proto.Field( proto.MESSAGE, number=8, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py index 8117c7e3cdb5..b653c08f71c9 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/page.py @@ -401,6 +401,11 @@ class EventHandler(proto.Message): The target flow to transition to. Format: ``projects//locations//agents//flows/``. + This field is a member of `oneof`_ ``target``. + target_playbook (str): + The target playbook to transition to. Format: + ``projects//locations//agents//playbooks/``. + This field is a member of `oneof`_ ``target``. """ @@ -427,6 +432,11 @@ class EventHandler(proto.Message): number=3, oneof="target", ) + target_playbook: str = proto.Field( + proto.STRING, + number=7, + oneof="target", + ) class TransitionRoute(proto.Message): diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/parameter_definition.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/parameter_definition.py new file mode 100644 index 000000000000..9257157bc1d5 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/parameter_definition.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "DataType", + "ParameterDefinition", + "TypeSchema", + "InlineSchema", + }, +) + + +class DataType(proto.Enum): + r"""Defines data types that are supported for inlined schemas. These + types are consistent with + [google.protobuf.Value][google.protobuf.Value]. + + Values: + DATA_TYPE_UNSPECIFIED (0): + Not specified. + STRING (1): + Represents any string value. + NUMBER (2): + Represents any number value. + BOOLEAN (3): + Represents a boolean value. + ARRAY (6): + Represents a repeated value. + """ + DATA_TYPE_UNSPECIFIED = 0 + STRING = 1 + NUMBER = 2 + BOOLEAN = 3 + ARRAY = 6 + + +class ParameterDefinition(proto.Message): + r"""Defines the properties of a parameter. + Used to define parameters used in the agent and the input / + output parameters for each fulfillment. + + Attributes: + name (str): + Required. Name of parameter. + type_ (google.cloud.dialogflowcx_v3.types.ParameterDefinition.ParameterType): + Type of parameter. + type_schema (google.cloud.dialogflowcx_v3.types.TypeSchema): + Optional. Type schema of parameter. + description (str): + Human-readable description of the parameter. + Limited to 300 characters. + """ + + class ParameterType(proto.Enum): + r"""Parameter types are used for validation. These types are consistent + with [google.protobuf.Value][google.protobuf.Value]. + + Values: + PARAMETER_TYPE_UNSPECIFIED (0): + Not specified. No validation will be + performed. + STRING (1): + Represents any string value. + NUMBER (2): + Represents any number value. + BOOLEAN (3): + Represents a boolean value. + NULL (4): + Represents a null value. + OBJECT (5): + Represents any object value. + LIST (6): + Represents a repeated value. + """ + PARAMETER_TYPE_UNSPECIFIED = 0 + STRING = 1 + NUMBER = 2 + BOOLEAN = 3 + NULL = 4 + OBJECT = 5 + LIST = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: ParameterType = proto.Field( + proto.ENUM, + number=2, + enum=ParameterType, + ) + type_schema: "TypeSchema" = proto.Field( + proto.MESSAGE, + number=4, + message="TypeSchema", + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + + +class TypeSchema(proto.Message): + r"""Encapsulates different type schema variations: either a + reference to an a schema that's already defined by a tool, or an + inline definition. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_schema (google.cloud.dialogflowcx_v3.types.InlineSchema): + Set if this is an inline schema definition. + + This field is a member of `oneof`_ ``schema``. + schema_reference (google.cloud.dialogflowcx_v3.types.TypeSchema.SchemaReference): + Set if this is a schema reference. + + This field is a member of `oneof`_ ``schema``. + """ + + class SchemaReference(proto.Message): + r"""A reference to the schema of an existing tool. + + Attributes: + tool (str): + The tool that contains this schema definition. Format: + ``projects//locations//agents//tools/``. + schema (str): + The name of the schema. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + schema: str = proto.Field( + proto.STRING, + number=2, + ) + + inline_schema: "InlineSchema" = proto.Field( + proto.MESSAGE, + number=1, + oneof="schema", + message="InlineSchema", + ) + schema_reference: SchemaReference = proto.Field( + proto.MESSAGE, + number=2, + oneof="schema", + message=SchemaReference, + ) + + +class InlineSchema(proto.Message): + r"""A type schema object that's specified inline. + + Attributes: + type_ (google.cloud.dialogflowcx_v3.types.DataType): + Data type of the schema. + items (google.cloud.dialogflowcx_v3.types.TypeSchema): + Schema of the elements if this is an ARRAY + type. + """ + + type_: "DataType" = proto.Field( + proto.ENUM, + number=1, + enum="DataType", + ) + items: "TypeSchema" = proto.Field( + proto.MESSAGE, + number=2, + message="TypeSchema", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/playbook.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/playbook.py new file mode 100644 index 000000000000..31dc94d8a209 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/playbook.py @@ -0,0 +1,956 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import import_strategy as gcdc_import_strategy +from google.cloud.dialogflowcx_v3.types import code_block as gcdc_code_block +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import fulfillment as gcdc_fulfillment +from google.cloud.dialogflowcx_v3.types import generative_settings +from google.cloud.dialogflowcx_v3.types import parameter_definition + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "CreatePlaybookRequest", + "DeletePlaybookRequest", + "ListPlaybooksRequest", + "ListPlaybooksResponse", + "GetPlaybookRequest", + "UpdatePlaybookRequest", + "Playbook", + "CreatePlaybookVersionRequest", + "PlaybookVersion", + "GetPlaybookVersionRequest", + "RestorePlaybookVersionRequest", + "RestorePlaybookVersionResponse", + "ListPlaybookVersionsRequest", + "ListPlaybookVersionsResponse", + "DeletePlaybookVersionRequest", + "ExportPlaybookRequest", + "ImportPlaybookRequest", + "PlaybookImportStrategy", + "ImportPlaybookResponse", + "ExportPlaybookResponse", + "Handler", + }, +) + + +class CreatePlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.CreatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook]. + + Attributes: + parent (str): + Required. The agent to create a playbook for. Format: + ``projects//locations//agents/``. + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + Required. The playbook to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + playbook: "Playbook" = proto.Field( + proto.MESSAGE, + number=2, + message="Playbook", + ) + + +class DeletePlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.DeletePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook]. + + Attributes: + name (str): + Required. The name of the playbook to delete. Format: + ``projects//locations//agents//playbooks/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPlaybooksRequest(proto.Message): + r"""The request message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + + Attributes: + parent (str): + Required. The agent to list playbooks from. 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: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPlaybooksResponse(proto.Message): + r"""The response message for + [Playbooks.ListPlaybooks][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks]. + + Attributes: + playbooks (MutableSequence[google.cloud.dialogflowcx_v3.types.Playbook]): + The list of playbooks. 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 + + playbooks: MutableSequence["Playbook"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Playbook", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.GetPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook]. + + Attributes: + name (str): + Required. The name of the playbook. Format: + ``projects//locations//agents//playbooks/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdatePlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.UpdatePlaybook][google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook]. + + Attributes: + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + Required. The playbook 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. + """ + + playbook: "Playbook" = proto.Field( + proto.MESSAGE, + number=1, + message="Playbook", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Playbook(proto.Message): + r"""Playbook is the basic building block to instruct the LLM how + to execute a certain task. + + A playbook consists of a goal to accomplish, an optional list of + step by step instructions (the step instruction may refers to + name of the custom or default plugin tools to use) to perform + the task, + a list of contextual input data to be passed in at the beginning + of the invoked, and a list of output parameters to store the + playbook result. + + Attributes: + name (str): + The unique identifier of the playbook. Format: + ``projects//locations//agents//playbooks/``. + display_name (str): + Required. The human-readable name of the + playbook, unique within an agent. + goal (str): + Required. High level description of the goal + the playbook intend to accomplish. A goal should + be concise since it's visible to other playbooks + that may reference this playbook. + input_parameter_definitions (MutableSequence[google.cloud.dialogflowcx_v3.types.ParameterDefinition]): + Optional. Defined structured input parameters + for this playbook. + output_parameter_definitions (MutableSequence[google.cloud.dialogflowcx_v3.types.ParameterDefinition]): + Optional. Defined structured output + parameters for this playbook. + instruction (google.cloud.dialogflowcx_v3.types.Playbook.Instruction): + Instruction to accomplish target goal. + token_count (int): + Output only. Estimated number of tokes + current playbook takes when sent to the LLM. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of initial + playbook creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the playbook version + was updated. + referenced_playbooks (MutableSequence[str]): + Output only. The resource name of other + playbooks referenced by the current playbook in + the instructions. + referenced_flows (MutableSequence[str]): + Output only. The resource name of flows + referenced by the current playbook in the + instructions. + referenced_tools (MutableSequence[str]): + Optional. The resource name of tools + referenced by the current playbook in the + instructions. If not provided explicitly, they + are will be implied using the tool being + referenced in goal and steps. + inline_actions (MutableSequence[str]): + Optional. Output only. Names of inline + actions scoped to this playbook. These actions + are in addition to those belonging to referenced + tools, child playbooks, and flows, e.g. actions + that are defined in the playbook's code block. + code_block (google.cloud.dialogflowcx_v3.types.CodeBlock): + Optional. The playbook's scoped code block, + which may implement handlers and actions. + llm_model_settings (google.cloud.dialogflowcx_v3.types.LlmModelSettings): + Optional. Llm model settings for the + playbook. + handlers (MutableSequence[google.cloud.dialogflowcx_v3.types.Handler]): + Optional. A list of registered handlers to + execuate based on the specified triggers. + playbook_type (google.cloud.dialogflowcx_v3.types.Playbook.PlaybookType): + Optional. Type of the playbook. + """ + + class PlaybookType(proto.Enum): + r"""Type of the playbook. + + Values: + PLAYBOOK_TYPE_UNSPECIFIED (0): + Unspecified type. Default to TASK. + TASK (1): + Task playbook. + ROUTINE (3): + Routine playbook. + """ + PLAYBOOK_TYPE_UNSPECIFIED = 0 + TASK = 1 + ROUTINE = 3 + + class Step(proto.Message): + r"""Message of single step execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Step instruction in text format. + + This field is a member of `oneof`_ ``instruction``. + steps (MutableSequence[google.cloud.dialogflowcx_v3.types.Playbook.Step]): + Sub-processing needed to execute the current + step. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="instruction", + ) + steps: MutableSequence["Playbook.Step"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Playbook.Step", + ) + + class Instruction(proto.Message): + r"""Message of the Instruction of the playbook. + + Attributes: + guidelines (str): + General guidelines for the playbook. These + are unstructured instructions that are not + directly part of the goal, e.g. "Always be + polite". It's valid for this text to be long and + used instead of steps altogether. + steps (MutableSequence[google.cloud.dialogflowcx_v3.types.Playbook.Step]): + Ordered list of step by step execution + instructions to accomplish target goal. + """ + + guidelines: str = proto.Field( + proto.STRING, + number=1, + ) + steps: MutableSequence["Playbook.Step"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Playbook.Step", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + goal: str = proto.Field( + proto.STRING, + number=3, + ) + input_parameter_definitions: MutableSequence[ + parameter_definition.ParameterDefinition + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=parameter_definition.ParameterDefinition, + ) + output_parameter_definitions: MutableSequence[ + parameter_definition.ParameterDefinition + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=parameter_definition.ParameterDefinition, + ) + instruction: Instruction = proto.Field( + proto.MESSAGE, + number=17, + message=Instruction, + ) + token_count: int = proto.Field( + proto.INT64, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + referenced_playbooks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + referenced_flows: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + referenced_tools: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + inline_actions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=22, + ) + code_block: gcdc_code_block.CodeBlock = proto.Field( + proto.MESSAGE, + number=21, + message=gcdc_code_block.CodeBlock, + ) + llm_model_settings: generative_settings.LlmModelSettings = proto.Field( + proto.MESSAGE, + number=14, + message=generative_settings.LlmModelSettings, + ) + handlers: MutableSequence["Handler"] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message="Handler", + ) + playbook_type: PlaybookType = proto.Field( + proto.ENUM, + number=19, + enum=PlaybookType, + ) + + +class CreatePlaybookVersionRequest(proto.Message): + r"""The request message for + [Playbooks.CreatePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion]. + + Attributes: + parent (str): + Required. The playbook to create a version for. Format: + ``projects//locations//agents//playbooks/``. + playbook_version (google.cloud.dialogflowcx_v3.types.PlaybookVersion): + Required. The playbook version to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + playbook_version: "PlaybookVersion" = proto.Field( + proto.MESSAGE, + number=2, + message="PlaybookVersion", + ) + + +class PlaybookVersion(proto.Message): + r"""Playbook version is a snapshot of the playbook at certain + timestamp. + + Attributes: + name (str): + The unique identifier of the playbook version. Format: + ``projects//locations//agents//playbooks//versions/``. + description (str): + Optional. The description of the playbook + version. + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + Output only. Snapshot of the playbook when + the playbook version is created. + examples (MutableSequence[google.cloud.dialogflowcx_v3.types.Example]): + Output only. Snapshot of the examples + belonging to the playbook when the playbook + version is created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the playbook version + was created or modified. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + playbook: "Playbook" = proto.Field( + proto.MESSAGE, + number=3, + message="Playbook", + ) + examples: MutableSequence[example.Example] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=example.Example, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class GetPlaybookVersionRequest(proto.Message): + r"""The request message for + [Playbooks.GetPlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion]. + + Attributes: + name (str): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//versions/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RestorePlaybookVersionRequest(proto.Message): + r"""The request message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + + Attributes: + name (str): + Required. The name of the playbook version. Format: + ``projects//locations//agents//playbooks//versions/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RestorePlaybookVersionResponse(proto.Message): + r"""The response message for + [Playbooks.RestorePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion]. + + Attributes: + playbook (google.cloud.dialogflowcx_v3.types.Playbook): + The updated playbook. + """ + + playbook: "Playbook" = proto.Field( + proto.MESSAGE, + number=2, + message="Playbook", + ) + + +class ListPlaybookVersionsRequest(proto.Message): + r"""The request message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + + Attributes: + parent (str): + Required. The playbook to list versions for. Format: + ``projects//locations//agents//playbooks/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPlaybookVersionsResponse(proto.Message): + r"""The response message for + [Playbooks.ListPlaybookVersions][google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions]. + + Attributes: + playbook_versions (MutableSequence[google.cloud.dialogflowcx_v3.types.PlaybookVersion]): + The list of playbook version. 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 + + playbook_versions: MutableSequence["PlaybookVersion"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PlaybookVersion", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeletePlaybookVersionRequest(proto.Message): + r"""The request message for + [Playbooks.DeletePlaybookVersion][google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion]. + + Attributes: + name (str): + Required. The name of the playbook version to delete. + Format: + ``projects//locations//agents//playbooks//versions/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportPlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + + Attributes: + name (str): + Required. The name of the playbook to export. Format: + ``projects//locations//agents//playbooks/``. + playbook_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the playbook to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized playbook is returned inline. + + Dialogflow performs a write operation for the Cloud Storage + object on the caller's behalf, so your request + authentication must have write permissions for the object. + For more information, see `Dialogflow access + control `__. + data_format (google.cloud.dialogflowcx_v3.types.ExportPlaybookRequest.DataFormat): + Optional. The data format of the exported agent. If not + specified, ``BLOB`` is assumed. + """ + + class DataFormat(proto.Enum): + r"""Data format of the exported playbook. + + Values: + DATA_FORMAT_UNSPECIFIED (0): + Unspecified format. + BLOB (1): + Flow content will be exported as raw bytes. + JSON (2): + Flow content will be exported in JSON format. + """ + DATA_FORMAT_UNSPECIFIED = 0 + BLOB = 1 + JSON = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + playbook_uri: str = proto.Field( + proto.STRING, + number=2, + ) + data_format: DataFormat = proto.Field( + proto.ENUM, + number=3, + enum=DataFormat, + ) + + +class ImportPlaybookRequest(proto.Message): + r"""The request message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The agent to import the playbook into. Format: + ``projects//locations//agents/``. + playbook_uri (str): + [Dialogflow access control] + (https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage). + + This field is a member of `oneof`_ ``playbook``. + playbook_content (bytes): + Uncompressed raw byte content for playbook. + + This field is a member of `oneof`_ ``playbook``. + import_strategy (google.cloud.dialogflowcx_v3.types.PlaybookImportStrategy): + Optional. Specifies the import strategy used + when resolving resource conflicts. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + playbook_uri: str = proto.Field( + proto.STRING, + number=2, + oneof="playbook", + ) + playbook_content: bytes = proto.Field( + proto.BYTES, + number=3, + oneof="playbook", + ) + import_strategy: "PlaybookImportStrategy" = proto.Field( + proto.MESSAGE, + number=4, + message="PlaybookImportStrategy", + ) + + +class PlaybookImportStrategy(proto.Message): + r"""The playbook import strategy used for resource conflict resolution + associated with an + [ImportPlaybookRequest][google.cloud.dialogflow.cx.v3.ImportPlaybookRequest]. + + Attributes: + main_playbook_import_strategy (google.cloud.dialogflowcx_v3.types.ImportStrategy): + Optional. Specifies the import strategy used when resolving + conflicts with the main playbook. If not specified, + 'CREATE_NEW' is assumed. + nested_resource_import_strategy (google.cloud.dialogflowcx_v3.types.ImportStrategy): + Optional. Specifies the import strategy used when resolving + referenced playbook/flow conflicts. If not specified, + 'CREATE_NEW' is assumed. + tool_import_strategy (google.cloud.dialogflowcx_v3.types.ImportStrategy): + Optional. Specifies the import strategy used when resolving + tool conflicts. If not specified, 'CREATE_NEW' is assumed. + This will be applied after the main playbook and nested + resource import strategies, meaning if the playbook that + references the tool is skipped, the tool will also be + skipped. + """ + + main_playbook_import_strategy: gcdc_import_strategy.ImportStrategy = proto.Field( + proto.ENUM, + number=4, + enum=gcdc_import_strategy.ImportStrategy, + ) + nested_resource_import_strategy: gcdc_import_strategy.ImportStrategy = proto.Field( + proto.ENUM, + number=5, + enum=gcdc_import_strategy.ImportStrategy, + ) + tool_import_strategy: gcdc_import_strategy.ImportStrategy = proto.Field( + proto.ENUM, + number=6, + enum=gcdc_import_strategy.ImportStrategy, + ) + + +class ImportPlaybookResponse(proto.Message): + r"""The response message for + [Playbooks.ImportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook]. + + Attributes: + playbook (str): + The unique identifier of the new playbook. Format: + ``projects//locations//agents//playbooks/``. + conflicting_resources (google.cloud.dialogflowcx_v3.types.ImportPlaybookResponse.ConflictingResources): + Info which resources have conflicts when + [REPORT_CONFLICTS][ImportPlaybookResponse.REPORT_CONFLICTS] + import strategy is set for all resources in + ImportPlaybookRequest. + """ + + class ConflictingResources(proto.Message): + r"""Conflicting resources detected during the import process. Only + filled when + [REPORT_CONFLICTS][ImportPlaybookResponse.REPORT_CONFLICTS] is set + in the request and there are conflicts in the display names. + + Attributes: + main_playbook_display_name (str): + Display name of conflicting main playbook. + nested_playbook_display_names (MutableSequence[str]): + Display names of conflicting nested + playbooks. + tool_display_names (MutableSequence[str]): + Display names of conflicting tools. + """ + + main_playbook_display_name: str = proto.Field( + proto.STRING, + number=1, + ) + nested_playbook_display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + tool_display_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + playbook: str = proto.Field( + proto.STRING, + number=1, + ) + conflicting_resources: ConflictingResources = proto.Field( + proto.MESSAGE, + number=2, + message=ConflictingResources, + ) + + +class ExportPlaybookResponse(proto.Message): + r"""The response message for + [Playbooks.ExportPlaybook][google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + playbook_uri (str): + The URI to a file containing the exported playbook. This + field is populated only if ``playbook_uri`` is specified in + [ExportPlaybookRequest][google.cloud.dialogflow.cx.v3.ExportPlaybookRequest]. + + This field is a member of `oneof`_ ``playbook``. + playbook_content (bytes): + Uncompressed raw byte content for playbook. + + This field is a member of `oneof`_ ``playbook``. + """ + + playbook_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="playbook", + ) + playbook_content: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="playbook", + ) + + +class Handler(proto.Message): + r"""Handler can be used to define custom logic to be executed + based on the user-specified triggers. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_handler (google.cloud.dialogflowcx_v3.types.Handler.EventHandler): + A handler triggered by event. + + This field is a member of `oneof`_ ``handler``. + lifecycle_handler (google.cloud.dialogflowcx_v3.types.Handler.LifecycleHandler): + A handler triggered during specific lifecycle + of the playbook execution. + + This field is a member of `oneof`_ ``handler``. + """ + + class EventHandler(proto.Message): + r"""A handler that is triggered by the specified + [event][google.cloud.dialogflow.cx.v3.Handler.EventHandler.event]. + + Attributes: + event (str): + Required. The name of the event that triggers + this handler. + condition (str): + Optional. The condition that must be + satisfied to trigger this handler. + fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + Required. The fulfillment to call when the + event occurs. + """ + + event: str = proto.Field( + proto.STRING, + number=1, + ) + condition: str = proto.Field( + proto.STRING, + number=3, + ) + fulfillment: gcdc_fulfillment.Fulfillment = proto.Field( + proto.MESSAGE, + number=2, + message=gcdc_fulfillment.Fulfillment, + ) + + class LifecycleHandler(proto.Message): + r"""A handler that is triggered on the specific + [lifecycle_stage][google.cloud.dialogflow.cx.v3.Handler.LifecycleHandler.lifecycle_stage] + of the playbook execution. + + Attributes: + lifecycle_stage (str): + Required. The name of the lifecycle stage that triggers this + handler. Supported values: + + - ``playbook-start`` + - ``pre-action-selection`` + - ``pre-action-execution`` + condition (str): + Optional. The condition that must be + satisfied to trigger this handler. + fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + Required. The fulfillment to call when this + handler is triggered. + """ + + lifecycle_stage: str = proto.Field( + proto.STRING, + number=1, + ) + condition: str = proto.Field( + proto.STRING, + number=2, + ) + fulfillment: gcdc_fulfillment.Fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=gcdc_fulfillment.Fulfillment, + ) + + event_handler: EventHandler = proto.Field( + proto.MESSAGE, + number=1, + oneof="handler", + message=EventHandler, + ) + lifecycle_handler: LifecycleHandler = proto.Field( + proto.MESSAGE, + number=3, + oneof="handler", + message=LifecycleHandler, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py index 4051d9e8b2d6..a3f4f6e5c09b 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/response_message.py @@ -20,6 +20,8 @@ from google.protobuf import struct_pb2 # type: ignore import proto # type: ignore +from google.cloud.dialogflowcx_v3.types import tool_call as gcdc_tool_call + __protobuf__ = proto.module( package="google.cloud.dialogflow.cx.v3", manifest={ @@ -120,6 +122,11 @@ class ResponseMessage(proto.Message): Represents info card for knowledge answers, to be better rendered in Dialogflow Messenger. + This field is a member of `oneof`_ ``message``. + tool_call (google.cloud.dialogflowcx_v3.types.ToolCall): + Returns the definition of a tool call that + should be executed by the client. + This field is a member of `oneof`_ ``message``. response_type (google.cloud.dialogflowcx_v3.types.ResponseMessage.ResponseType): Response type. @@ -474,6 +481,12 @@ class KnowledgeInfoCard(proto.Message): oneof="message", message=KnowledgeInfoCard, ) + tool_call: gcdc_tool_call.ToolCall = proto.Field( + proto.MESSAGE, + number=22, + oneof="message", + message=gcdc_tool_call.ToolCall, + ) response_type: ResponseType = proto.Field( proto.ENUM, number=4, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py index 088a8f89b5bd..bfe296329370 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/safety_settings.py @@ -31,10 +31,43 @@ class SafetySettings(proto.Message): r"""Settings for Generative Safety. Attributes: + default_banned_phrase_match_strategy (google.cloud.dialogflowcx_v3.types.SafetySettings.PhraseMatchStrategy): + Optional. Default phrase match strategy for + banned phrases. banned_phrases (MutableSequence[google.cloud.dialogflowcx_v3.types.SafetySettings.Phrase]): Banned phrases for generated text. + rai_settings (google.cloud.dialogflowcx_v3.types.SafetySettings.RaiSettings): + Optional. Settings for Responsible AI checks. + default_rai_settings (google.cloud.dialogflowcx_v3.types.SafetySettings.RaiSettings): + Optional. Immutable. Default RAI settings to + be annotated on the agent, so that users will be + able to restore their RAI configurations to the + default settings. Read-only field for the API + proto only. + prompt_security_settings (google.cloud.dialogflowcx_v3.types.SafetySettings.PromptSecuritySettings): + Optional. Settings for prompt security + checks. """ + class PhraseMatchStrategy(proto.Enum): + r"""Strategy for matching phrases. + + Values: + PHRASE_MATCH_STRATEGY_UNSPECIFIED (0): + Unspecified, defaults to PARTIAL_MATCH. + PARTIAL_MATCH (1): + Text that contains the phrase as a substring + will be matched, e.g. "foo" will match + "afoobar". + WORD_MATCH (2): + Text that contains the tokenized words of the + phrase will be matched, e.g. "foo" will match "a + foo bar" and "foo bar", but not "foobar". + """ + PHRASE_MATCH_STRATEGY_UNSPECIFIED = 0 + PARTIAL_MATCH = 1 + WORD_MATCH = 2 + class Phrase(proto.Message): r"""Text input which can be used for prompt or banned phrases. @@ -55,11 +88,127 @@ class Phrase(proto.Message): number=2, ) + class RaiSettings(proto.Message): + r"""Settings for Responsible AI. + + Attributes: + category_filters (MutableSequence[google.cloud.dialogflowcx_v3.types.SafetySettings.RaiSettings.CategoryFilter]): + Optional. RAI blocking configurations. + """ + + class SafetyFilterLevel(proto.Enum): + r"""Sensitivity level for RAI categories. + + Values: + SAFETY_FILTER_LEVEL_UNSPECIFIED (0): + Unspecified -- uses default sensitivity + levels. + BLOCK_NONE (1): + Block no text -- effectively disables the + category. + BLOCK_FEW (2): + Block a few suspicious texts. + BLOCK_SOME (3): + Block some suspicious texts. + BLOCK_MOST (4): + Block most suspicious texts. + """ + SAFETY_FILTER_LEVEL_UNSPECIFIED = 0 + BLOCK_NONE = 1 + BLOCK_FEW = 2 + BLOCK_SOME = 3 + BLOCK_MOST = 4 + + class SafetyCategory(proto.Enum): + r"""RAI categories to configure. + + Values: + SAFETY_CATEGORY_UNSPECIFIED (0): + Unspecified. + DANGEROUS_CONTENT (1): + Dangerous content. + HATE_SPEECH (2): + Hate speech. + HARASSMENT (3): + Harassment. + SEXUALLY_EXPLICIT_CONTENT (4): + Sexually explicit content. + """ + SAFETY_CATEGORY_UNSPECIFIED = 0 + DANGEROUS_CONTENT = 1 + HATE_SPEECH = 2 + HARASSMENT = 3 + SEXUALLY_EXPLICIT_CONTENT = 4 + + class CategoryFilter(proto.Message): + r"""Configuration of the sensitivity level for blocking an RAI + category. + + Attributes: + category (google.cloud.dialogflowcx_v3.types.SafetySettings.RaiSettings.SafetyCategory): + RAI category to configure. + filter_level (google.cloud.dialogflowcx_v3.types.SafetySettings.RaiSettings.SafetyFilterLevel): + Blocking sensitivity level to configure for + the RAI category. + """ + + category: "SafetySettings.RaiSettings.SafetyCategory" = proto.Field( + proto.ENUM, + number=1, + enum="SafetySettings.RaiSettings.SafetyCategory", + ) + filter_level: "SafetySettings.RaiSettings.SafetyFilterLevel" = proto.Field( + proto.ENUM, + number=2, + enum="SafetySettings.RaiSettings.SafetyFilterLevel", + ) + + category_filters: MutableSequence[ + "SafetySettings.RaiSettings.CategoryFilter" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SafetySettings.RaiSettings.CategoryFilter", + ) + + class PromptSecuritySettings(proto.Message): + r"""Settings for prompt security checks. + + Attributes: + enable_prompt_security (bool): + Optional. Enable prompt security checks. + """ + + enable_prompt_security: bool = proto.Field( + proto.BOOL, + number=1, + ) + + default_banned_phrase_match_strategy: PhraseMatchStrategy = proto.Field( + proto.ENUM, + number=4, + enum=PhraseMatchStrategy, + ) banned_phrases: MutableSequence[Phrase] = proto.RepeatedField( proto.MESSAGE, number=1, message=Phrase, ) + rai_settings: RaiSettings = proto.Field( + proto.MESSAGE, + number=2, + message=RaiSettings, + ) + default_rai_settings: RaiSettings = proto.Field( + proto.MESSAGE, + number=3, + message=RaiSettings, + ) + prompt_security_settings: PromptSecuritySettings = proto.Field( + proto.MESSAGE, + number=8, + message=PromptSecuritySettings, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py index 9dad43c5b3ac..2d1e3e5dcdc8 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -369,7 +369,10 @@ class AudioExportSettings(proto.Message): should have the permission of storage.buckets.setIamPolicy. audio_export_pattern (str): - Filename pattern for exported audio. + Filename pattern for exported audio. {conversation} and + {timestamp} are placeholders that will be replaced with the + conversation ID and epoch micros of the conversation. For + example, "{conversation}/recording\_{timestamp}.mulaw". enable_audio_redaction (bool): Enable audio redaction if it is true. Note that this only redacts end-user audio data; diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py index 813608c8896e..44ee98493768 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/session.py @@ -24,11 +24,17 @@ from google.type import latlng_pb2 # type: ignore import proto # type: ignore -from google.cloud.dialogflowcx_v3.types import audio_config, data_store_connection, flow +from google.cloud.dialogflowcx_v3.types import ( + audio_config, + data_store_connection, + flow, + generative_settings, +) from google.cloud.dialogflowcx_v3.types import ( page, response_message, session_entity_type, + tool_call, ) from google.cloud.dialogflowcx_v3.types import ( advanced_settings as gcdc_advanced_settings, @@ -38,6 +44,7 @@ __protobuf__ = proto.module( package="google.cloud.dialogflow.cx.v3", manifest={ + "DetectIntentResponseView", "AnswerFeedback", "SubmitAnswerFeedbackRequest", "DetectIntentRequest", @@ -68,6 +75,33 @@ ) +class DetectIntentResponseView(proto.Enum): + r"""The response view specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] to return. + + Values: + DETECT_INTENT_RESPONSE_VIEW_UNSPECIFIED (0): + Not specified. ``DETECT_INTENT_RESPONSE_VIEW_DEFAULT`` will + be used. + DETECT_INTENT_RESPONSE_VIEW_FULL (1): + Full response view includes all fields. + DETECT_INTENT_RESPONSE_VIEW_BASIC (2): + Basic response view omits the following fields: + ----------------------------------------------- + + [QueryResult.diagnostic_info][google.cloud.dialogflow.cx.v3.QueryResult.diagnostic_info] + DETECT_INTENT_RESPONSE_VIEW_DEFAULT (3): + Default response view omits the following fields: + ------------------------------------------------- + + [QueryResult.trace_blocks][google.cloud.dialogflow.cx.v3.QueryResult.trace_blocks] + """ + DETECT_INTENT_RESPONSE_VIEW_UNSPECIFIED = 0 + DETECT_INTENT_RESPONSE_VIEW_FULL = 1 + DETECT_INTENT_RESPONSE_VIEW_BASIC = 2 + DETECT_INTENT_RESPONSE_VIEW_DEFAULT = 3 + + class AnswerFeedback(proto.Message): r"""Stores information about feedback provided by users about a response. @@ -210,6 +244,11 @@ class DetectIntentRequest(proto.Message): output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): Instructs the speech synthesizer how to generate the output audio. + response_view (google.cloud.dialogflowcx_v3.types.DetectIntentResponseView): + Optional. Specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] to + return. If not set, the default is + DETECT_INTENT_RESPONSE_VIEW_FULL. """ session: str = proto.Field( @@ -231,6 +270,11 @@ class DetectIntentRequest(proto.Message): number=4, message=audio_config.OutputAudioConfig, ) + response_view: "DetectIntentResponseView" = proto.Field( + proto.ENUM, + number=9, + enum="DetectIntentResponseView", + ) class DetectIntentResponse(proto.Message): @@ -387,6 +431,11 @@ class StreamingDetectIntentRequest(proto.Message): enable_debugging_info (bool): If true, ``StreamingDetectIntentResponse.debugging_info`` will get populated. + response_view (google.cloud.dialogflowcx_v3.types.DetectIntentResponseView): + Optional. Specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] to + return. If not set, the default is + DETECT_INTENT_RESPONSE_VIEW_FULL. """ session: str = proto.Field( @@ -416,6 +465,11 @@ class StreamingDetectIntentRequest(proto.Message): proto.BOOL, number=8, ) + response_view: "DetectIntentResponseView" = proto.Field( + proto.ENUM, + number=16, + enum="DetectIntentResponseView", + ) class CloudConversationDebuggingInfo(proto.Message): @@ -846,6 +900,15 @@ class QueryParameters(proto.Message): - MapValue value: If parameter's entity type is a composite entity then use map from composite entity property names to property values, otherwise, use parameter value. + parameter_scope (str): + Scope for the parameters. If not specified, parameters will + be treated as session parameters. Parameters with custom + scope will not be put into [session + parameters][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. + + You can reference the parameters with custom scope in the + agent with the following format: + $parameter-scope.params.parameter-id. current_page (str): The unique identifier of the [page][google.cloud.dialogflow.cx.v3.Page] to override the @@ -891,6 +954,18 @@ class QueryParameters(proto.Message): of flow X will go through version 1 regardless of the version configuration in the environment. Each flow can have at most one version specified in this list. + current_playbook (str): + Optional. The unique identifier of the + [playbook][google.cloud.dialogflow.cx.v3.Playbook] to start + or continue the session with. If ``current_playbook`` is + specified, the previous state of the session will be ignored + by Dialogflow. + + Format: + ``projects//locations//agents//playbooks/``. + llm_model_settings (google.cloud.dialogflowcx_v3.types.LlmModelSettings): + Optional. Use the specified LLM model + settings for processing the request. channel (str): The channel which this query is for. @@ -967,6 +1042,10 @@ class QueryParameters(proto.Message): number=5, message=struct_pb2.Struct, ) + parameter_scope: str = proto.Field( + proto.STRING, + number=12, + ) current_page: str = proto.Field( proto.STRING, number=6, @@ -988,6 +1067,15 @@ class QueryParameters(proto.Message): proto.STRING, number=14, ) + current_playbook: str = proto.Field( + proto.STRING, + number=19, + ) + llm_model_settings: generative_settings.LlmModelSettings = proto.Field( + proto.MESSAGE, + number=21, + message=generative_settings.LlmModelSettings, + ) channel: str = proto.Field( proto.STRING, number=15, @@ -1338,6 +1426,10 @@ class QueryInput(proto.Message): dtmf (google.cloud.dialogflowcx_v3.types.DtmfInput): The DTMF event to be handled. + This field is a member of `oneof`_ ``input``. + tool_call_result (google.cloud.dialogflowcx_v3.types.ToolCallResult): + The results of a tool executed by the client. + This field is a member of `oneof`_ ``input``. language_code (str): Required. The language of the input. See `Language @@ -1377,6 +1469,12 @@ class QueryInput(proto.Message): oneof="input", message="DtmfInput", ) + tool_call_result: tool_call.ToolCallResult = proto.Field( + proto.MESSAGE, + number=11, + oneof="input", + message=tool_call.ToolCallResult, + ) language_code: str = proto.Field( proto.STRING, number=4, @@ -1454,18 +1552,6 @@ class QueryResult(proto.Message): client. Responses vary from simple text messages to more sophisticated, structured payloads used to drive complex logic. - webhook_ids (MutableSequence[str]): - The list of webhook ids in the order of call - sequence. - webhook_display_names (MutableSequence[str]): - The list of webhook display names in the - order of call sequence. - webhook_latencies (MutableSequence[google.protobuf.duration_pb2.Duration]): - The list of webhook latencies in the order of - call sequence. - webhook_tags (MutableSequence[str]): - The list of webhook tags in the order of call - sequence. webhook_statuses (MutableSequence[google.rpc.status_pb2.Status]): The list of webhook call status in the order of call sequence. @@ -1593,23 +1679,6 @@ class QueryResult(proto.Message): number=4, message=response_message.ResponseMessage, ) - webhook_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=25, - ) - webhook_display_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=26, - ) - webhook_latencies: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=duration_pb2.Duration, - ) - webhook_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=29, - ) webhook_statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, number=13, @@ -1844,7 +1913,8 @@ class MatchType(proto.Enum): The query was matched to a Knowledge Connector answer. PLAYBOOK (9): - The query was handled by a [``Playbook``][Playbook]. + The query was handled by a + [``Playbook``][google.cloud.dialogflow.cx.v3.Playbook]. """ MATCH_TYPE_UNSPECIFIED = 0 INTENT = 1 diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool.py new file mode 100644 index 000000000000..138d1547d4ad --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool.py @@ -0,0 +1,956 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +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 proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import data_store_connection + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "CreateToolRequest", + "ListToolsRequest", + "ListToolsResponse", + "GetToolRequest", + "UpdateToolRequest", + "DeleteToolRequest", + "Tool", + "ListToolVersionsRequest", + "ListToolVersionsResponse", + "CreateToolVersionRequest", + "GetToolVersionRequest", + "DeleteToolVersionRequest", + "RestoreToolVersionRequest", + "RestoreToolVersionResponse", + "ToolVersion", + }, +) + + +class CreateToolRequest(proto.Message): + r"""The request message for + [Tools.CreateTool][google.cloud.dialogflow.cx.v3.Tools.CreateTool]. + + Attributes: + parent (str): + Required. The agent to create a Tool for. Format: + ``projects//locations//agents/``. + tool (google.cloud.dialogflowcx_v3.types.Tool): + Required. The Tool to be created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=2, + message="Tool", + ) + + +class ListToolsRequest(proto.Message): + r"""The request message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + + Attributes: + parent (str): + Required. The agent to list the Tools from. 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: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListToolsResponse(proto.Message): + r"""The response message for + [Tools.ListTools][google.cloud.dialogflow.cx.v3.Tools.ListTools]. + + Attributes: + tools (MutableSequence[google.cloud.dialogflowcx_v3.types.Tool]): + The list of Tools. 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 + + tools: MutableSequence["Tool"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Tool", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetToolRequest(proto.Message): + r"""The request message for + [Tools.GetTool][google.cloud.dialogflow.cx.v3.Tools.GetTool]. + + Attributes: + name (str): + Required. The name of the Tool. Format: + ``projects//locations//agents//tools/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateToolRequest(proto.Message): + r"""The request message for + [Tools.UpdateTool][google.cloud.dialogflow.cx.v3.Tools.UpdateTool]. + + Attributes: + tool (google.cloud.dialogflowcx_v3.types.Tool): + Required. The Tool to be updated. + 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. + """ + + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=1, + message="Tool", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteToolRequest(proto.Message): + r"""The request message for + [Tools.DeleteTool][google.cloud.dialogflow.cx.v3.Tools.DeleteTool]. + + Attributes: + name (str): + Required. The name of the Tool to be deleted. Format: + ``projects//locations//agents//tools/``. + force (bool): + This field has no effect for Tools not being used. For Tools + that are used: + + - 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 + tool, as well as any references to the tool. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class Tool(proto.Message): + r"""A tool provides a list of actions which are available to the + [Playbook][google.cloud.dialogflow.cx.v3.Playbook] to attain its + goal. A Tool consists of a description of the tool's usage and a + specification of the tool which contains the schema and + authentication information. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The unique identifier of the Tool. Format: + ``projects//locations//agents//tools/``. + display_name (str): + Required. The human-readable name of the + Tool, unique within an agent. + description (str): + Required. High level description of the Tool + and its usage. + open_api_spec (google.cloud.dialogflowcx_v3.types.Tool.OpenApiTool): + OpenAPI specification of the Tool. + + This field is a member of `oneof`_ ``specification``. + data_store_spec (google.cloud.dialogflowcx_v3.types.Tool.DataStoreTool): + Data store search tool specification. + + This field is a member of `oneof`_ ``specification``. + function_spec (google.cloud.dialogflowcx_v3.types.Tool.FunctionTool): + Client side executed function specification. + + This field is a member of `oneof`_ ``specification``. + tool_type (google.cloud.dialogflowcx_v3.types.Tool.ToolType): + Output only. The tool type. + """ + + class ToolType(proto.Enum): + r"""Represents the type of the tool. + + Values: + TOOL_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + CUSTOMIZED_TOOL (1): + Customer provided tool. + BUILTIN_TOOL (2): + First party built-in tool created by + Dialogflow which cannot be modified. + """ + TOOL_TYPE_UNSPECIFIED = 0 + CUSTOMIZED_TOOL = 1 + BUILTIN_TOOL = 2 + + class OpenApiTool(proto.Message): + r"""An OpenAPI tool is a way to provide the Tool specifications + in the Open API schema format. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text_schema (str): + Required. The OpenAPI schema specified as a + text. + + This field is a member of `oneof`_ ``schema``. + authentication (google.cloud.dialogflowcx_v3.types.Tool.Authentication): + Optional. Authentication information required + by the API. + tls_config (google.cloud.dialogflowcx_v3.types.Tool.TLSConfig): + Optional. TLS configuration for the HTTPS + verification. + service_directory_config (google.cloud.dialogflowcx_v3.types.Tool.ServiceDirectoryConfig): + Optional. Service Directory configuration. + """ + + text_schema: str = proto.Field( + proto.STRING, + number=1, + oneof="schema", + ) + authentication: "Tool.Authentication" = proto.Field( + proto.MESSAGE, + number=2, + message="Tool.Authentication", + ) + tls_config: "Tool.TLSConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="Tool.TLSConfig", + ) + service_directory_config: "Tool.ServiceDirectoryConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="Tool.ServiceDirectoryConfig", + ) + + class DataStoreTool(proto.Message): + r"""A DataStoreTool is a way to provide specifications needed to + search a list of data stores. + + Attributes: + data_store_connections (MutableSequence[google.cloud.dialogflowcx_v3.types.DataStoreConnection]): + Required. List of data stores to search. + fallback_prompt (google.cloud.dialogflowcx_v3.types.Tool.DataStoreTool.FallbackPrompt): + Required. Fallback prompt configurations to + use. + """ + + class FallbackPrompt(proto.Message): + r"""A FallbackPrompt is a way to provide specifications for the + Data Store fallback prompt when generating responses. + + """ + + data_store_connections: MutableSequence[ + data_store_connection.DataStoreConnection + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data_store_connection.DataStoreConnection, + ) + fallback_prompt: "Tool.DataStoreTool.FallbackPrompt" = proto.Field( + proto.MESSAGE, + number=3, + message="Tool.DataStoreTool.FallbackPrompt", + ) + + class FunctionTool(proto.Message): + r"""A Function tool describes the functions to be invoked on the + client side. + + Attributes: + input_schema (google.protobuf.struct_pb2.Struct): + Optional. The JSON schema is encapsulated in a + [google.protobuf.Struct][google.protobuf.Struct] to describe + the input of the function. This input is a JSON object that + contains the function's parameters as properties of the + object. + output_schema (google.protobuf.struct_pb2.Struct): + Optional. The JSON schema is encapsulated in a + [google.protobuf.Struct][google.protobuf.Struct] to describe + the output of the function. This output is a JSON object + that contains the function's parameters as properties of the + object. + """ + + input_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + output_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + + class Authentication(proto.Message): + r"""Authentication information required for API calls + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + api_key_config (google.cloud.dialogflowcx_v3.types.Tool.Authentication.ApiKeyConfig): + Config for API key auth. + + This field is a member of `oneof`_ ``auth_config``. + oauth_config (google.cloud.dialogflowcx_v3.types.Tool.Authentication.OAuthConfig): + Config for OAuth. + + This field is a member of `oneof`_ ``auth_config``. + service_agent_auth_config (google.cloud.dialogflowcx_v3.types.Tool.Authentication.ServiceAgentAuthConfig): + Config for `Diglogflow service + agent `__ + auth. + + This field is a member of `oneof`_ ``auth_config``. + bearer_token_config (google.cloud.dialogflowcx_v3.types.Tool.Authentication.BearerTokenConfig): + Config for bearer token auth. + + This field is a member of `oneof`_ ``auth_config``. + service_account_auth_config (google.cloud.dialogflowcx_v3.types.Tool.Authentication.ServiceAccountAuthConfig): + Configuration for service account + authentication. + + This field is a member of `oneof`_ ``auth_config``. + """ + + class RequestLocation(proto.Enum): + r"""The location of the API key in the request. + + Values: + REQUEST_LOCATION_UNSPECIFIED (0): + Default value. This value is unused. + HEADER (1): + Represents the key in http header. + QUERY_STRING (2): + Represents the key in query string. + """ + REQUEST_LOCATION_UNSPECIFIED = 0 + HEADER = 1 + QUERY_STRING = 2 + + class ApiKeyConfig(proto.Message): + r"""Config for authentication with API key. + + Attributes: + key_name (str): + Required. The parameter name or the header + name of the API key. E.g., If the API request is + "https://example.com/act?X-Api-Key=", + "X-Api-Key" would be the parameter name. + api_key (str): + Optional. The API key. If the ``secret_version_for_api_key`` + field is set, this field will be ignored. + secret_version_for_api_key (str): + Optional. The name of the SecretManager secret version + resource storing the API key. If this field is set, the + ``api_key`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + request_location (google.cloud.dialogflowcx_v3.types.Tool.Authentication.RequestLocation): + Required. Key location in the request. + """ + + key_name: str = proto.Field( + proto.STRING, + number=1, + ) + api_key: str = proto.Field( + proto.STRING, + number=2, + ) + secret_version_for_api_key: str = proto.Field( + proto.STRING, + number=4, + ) + request_location: "Tool.Authentication.RequestLocation" = proto.Field( + proto.ENUM, + number=3, + enum="Tool.Authentication.RequestLocation", + ) + + class OAuthConfig(proto.Message): + r"""Config for authentication with OAuth. + + Attributes: + oauth_grant_type (google.cloud.dialogflowcx_v3.types.Tool.Authentication.OAuthConfig.OauthGrantType): + Required. OAuth grant types. + client_id (str): + Required. The client ID from the OAuth + provider. + client_secret (str): + Optional. The client secret from the OAuth provider. If the + ``secret_version_for_client_secret`` field is set, this + field will be ignored. + secret_version_for_client_secret (str): + Optional. The name of the SecretManager secret version + resource storing the client secret. If this field is set, + the ``client_secret`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + token_endpoint (str): + Required. The token endpoint in the OAuth + provider to exchange for an access token. + scopes (MutableSequence[str]): + Optional. The OAuth scopes to grant. + """ + + class OauthGrantType(proto.Enum): + r"""OAuth grant types. Only `client credential + grant `__ is + supported. + + Values: + OAUTH_GRANT_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + CLIENT_CREDENTIAL (1): + Represents the `client credential + flow `__. + """ + OAUTH_GRANT_TYPE_UNSPECIFIED = 0 + CLIENT_CREDENTIAL = 1 + + oauth_grant_type: "Tool.Authentication.OAuthConfig.OauthGrantType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="Tool.Authentication.OAuthConfig.OauthGrantType", + ) + ) + client_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_secret: str = proto.Field( + proto.STRING, + number=3, + ) + secret_version_for_client_secret: str = proto.Field( + proto.STRING, + number=6, + ) + token_endpoint: str = proto.Field( + proto.STRING, + number=4, + ) + scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + class ServiceAgentAuthConfig(proto.Message): + r"""Config for auth using `Diglogflow service + agent `__. + + Attributes: + service_agent_auth (google.cloud.dialogflowcx_v3.types.Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth): + Optional. Indicate the auth token type generated from the + `Diglogflow service + agent `__. + The generated token is sent in the Authorization header. + """ + + class ServiceAgentAuth(proto.Enum): + r"""Indicate the auth token type generated from the `Diglogflow service + agent `__. + + Values: + SERVICE_AGENT_AUTH_UNSPECIFIED (0): + Service agent auth type unspecified. Default to ID_TOKEN. + ID_TOKEN (1): + Use `ID + token `__ + generated from service agent. This can be used to access + Cloud Function and Cloud Run after you grant Invoker role to + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com``. + ACCESS_TOKEN (2): + Use `access + token `__ + generated from service agent. This can be used to access + other Google Cloud APIs after you grant required roles to + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com``. + """ + SERVICE_AGENT_AUTH_UNSPECIFIED = 0 + ID_TOKEN = 1 + ACCESS_TOKEN = 2 + + service_agent_auth: "Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth" = proto.Field( + proto.ENUM, + number=1, + enum="Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth", + ) + + class BearerTokenConfig(proto.Message): + r"""Config for authentication using bearer token. + + Attributes: + token (str): + Optional. The text token appended to the text ``Bearer`` to + the request Authorization header. `Session parameters + reference `__ + can be used to pass the token dynamically, e.g. + ``$session.params.parameter-id``. + secret_version_for_token (str): + Optional. The name of the SecretManager secret version + resource storing the Bearer token. If this field is set, the + ``token`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + secret_version_for_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class ServiceAccountAuthConfig(proto.Message): + r"""Configuration for authentication using a service account. + + Attributes: + service_account (str): + Required. The email address of the service account used to + authenticate the tool call. Dialogflow uses this service + account to exchange an access token and the access token is + then sent in the ``Authorization`` header of the tool + request. + + The service account must have the + ``roles/iam.serviceAccountTokenCreator`` role granted to the + `Dialogflow service + agent `__. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + + api_key_config: "Tool.Authentication.ApiKeyConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="auth_config", + message="Tool.Authentication.ApiKeyConfig", + ) + oauth_config: "Tool.Authentication.OAuthConfig" = proto.Field( + proto.MESSAGE, + number=2, + oneof="auth_config", + message="Tool.Authentication.OAuthConfig", + ) + service_agent_auth_config: "Tool.Authentication.ServiceAgentAuthConfig" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="auth_config", + message="Tool.Authentication.ServiceAgentAuthConfig", + ) + ) + bearer_token_config: "Tool.Authentication.BearerTokenConfig" = proto.Field( + proto.MESSAGE, + number=4, + oneof="auth_config", + message="Tool.Authentication.BearerTokenConfig", + ) + service_account_auth_config: "Tool.Authentication.ServiceAccountAuthConfig" = ( + proto.Field( + proto.MESSAGE, + number=5, + oneof="auth_config", + message="Tool.Authentication.ServiceAccountAuthConfig", + ) + ) + + class TLSConfig(proto.Message): + r"""The TLS configuration. + + Attributes: + ca_certs (MutableSequence[google.cloud.dialogflowcx_v3.types.Tool.TLSConfig.CACert]): + Required. Specifies a list of allowed custom + CA certificates for HTTPS verification. + """ + + class CACert(proto.Message): + r"""The CA certificate. + + Attributes: + display_name (str): + Required. The name of the allowed custom CA + certificates. This can be used to disambiguate + the custom CA certificates. + cert (bytes): + Required. The allowed custom CA certificates (in DER format) + for HTTPS verification. This overrides the default SSL trust + store. If this is empty or unspecified, Dialogflow will use + Google's default trust store to verify certificates. N.B. + Make sure the HTTPS server certificates are signed with + "subject alt name". For instance a certificate can be + self-signed using the following command: + + :: + + openssl x509 -req -days 200 -in example.com.csr \ + -signkey example.com.key \ + -out example.com.crt \ + -extfile <(printf "\nsubjectAltName='DNS:www.example.com'") + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + cert: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + ca_certs: MutableSequence["Tool.TLSConfig.CACert"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Tool.TLSConfig.CACert", + ) + + class ServiceDirectoryConfig(proto.Message): + r"""Configuration for tools using Service Directory. + + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``LocationID`` of the service directory must be the same as + the location of the agent. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + open_api_spec: OpenApiTool = proto.Field( + proto.MESSAGE, + number=4, + oneof="specification", + message=OpenApiTool, + ) + data_store_spec: DataStoreTool = proto.Field( + proto.MESSAGE, + number=8, + oneof="specification", + message=DataStoreTool, + ) + function_spec: FunctionTool = proto.Field( + proto.MESSAGE, + number=13, + oneof="specification", + message=FunctionTool, + ) + tool_type: ToolType = proto.Field( + proto.ENUM, + number=12, + enum=ToolType, + ) + + +class ListToolVersionsRequest(proto.Message): + r"""The request message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + + Attributes: + parent (str): + Required. The parent of the tool versions. Format: + ``projects//locations//agents//tools/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListToolVersionsResponse(proto.Message): + r"""The response message for + [Tools.ListToolVersions][google.cloud.dialogflow.cx.v3.Tools.ListToolVersions]. + + Attributes: + tool_versions (MutableSequence[google.cloud.dialogflowcx_v3.types.ToolVersion]): + The list of tool versions. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + tool_versions: MutableSequence["ToolVersion"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ToolVersion", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateToolVersionRequest(proto.Message): + r"""The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + The request message for + [Tools.CreateToolVersion][google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion]. + + Attributes: + parent (str): + Required. The tool to create a version for. Format: + ``projects//locations//agents//tools/``. + tool_version (google.cloud.dialogflowcx_v3.types.ToolVersion): + Required. The tool version to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tool_version: "ToolVersion" = proto.Field( + proto.MESSAGE, + number=2, + message="ToolVersion", + ) + + +class GetToolVersionRequest(proto.Message): + r"""The request message for + [Tools.GetToolVersion][google.cloud.dialogflow.cx.v3.Tools.GetToolVersion]. + + Attributes: + name (str): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//versions/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteToolVersionRequest(proto.Message): + r"""The request message for + [Tools.DeleteToolVersion][google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion]. + + Attributes: + name (str): + Required. The name of the tool version to delete. Format: + ``projects//locations//agents//tools//versions/``. + force (bool): + Optional. This field has no effect for Tools not being used. + For Tools that are used: + + - 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 + tool, as well as any references to the tool. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class RestoreToolVersionRequest(proto.Message): + r"""The request message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + + Attributes: + name (str): + Required. The name of the tool version. Format: + ``projects//locations//agents//tools//versions/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RestoreToolVersionResponse(proto.Message): + r"""The response message for + [Tools.RestoreToolVersion][google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion]. + + Attributes: + tool (google.cloud.dialogflowcx_v3.types.Tool): + The updated tool. + """ + + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=2, + message="Tool", + ) + + +class ToolVersion(proto.Message): + r"""Tool version is a snapshot of the tool at certain timestamp. + + Attributes: + name (str): + Identifier. The unique identifier of the tool version. + Format: + ``projects//locations//agents//tools//versions/``. + display_name (str): + Required. The display name of the tool + version. + tool (google.cloud.dialogflowcx_v3.types.Tool): + Required. Snapshot of the tool to be + associated with this version. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the tool version was + created or modified. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the tool version was + created or modified. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=3, + message="Tool", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool_call.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool_call.py new file mode 100644 index 000000000000..eeb8cff5eaeb --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/tool_call.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "ToolCall", + "ToolCallResult", + }, +) + + +class ToolCall(proto.Message): + r"""Represents a call of a specific tool's action with the + specified inputs. + + Attributes: + tool (str): + Required. The [tool][google.cloud.dialogflow.cx.v3.Tool] + associated with this call. Format: + ``projects//locations//agents//tools/``. + action (str): + Required. The name of the tool's action + associated with this call. + input_parameters (google.protobuf.struct_pb2.Struct): + Optional. The action's input parameters. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + action: str = proto.Field( + proto.STRING, + number=2, + ) + input_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ToolCallResult(proto.Message): + r"""The result of calling a tool's action that has been executed + by the client. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Required. The [tool][google.cloud.dialogflow.cx.v3.Tool] + associated with this call. Format: + ``projects//locations//agents//tools/``. + action (str): + Required. The name of the tool's action + associated with this call. + error (google.cloud.dialogflowcx_v3.types.ToolCallResult.Error): + The tool call's error. + + This field is a member of `oneof`_ ``result``. + output_parameters (google.protobuf.struct_pb2.Struct): + The tool call's output parameters. + + This field is a member of `oneof`_ ``result``. + """ + + class Error(proto.Message): + r"""An error produced by the tool call. + + Attributes: + message (str): + Optional. The error message of the function. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + action: str = proto.Field( + proto.STRING, + number=2, + ) + error: Error = proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message=Error, + ) + output_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + oneof="result", + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/trace.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/trace.py new file mode 100644 index 000000000000..3adaac9e764b --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/trace.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.cx.v3", + manifest={ + "OutputState", + "PlaybookInput", + "PlaybookOutput", + "Action", + "UserUtterance", + "AgentUtterance", + "ToolUse", + "PlaybookInvocation", + "FlowInvocation", + "PlaybookTransition", + "FlowTransition", + }, +) + + +class OutputState(proto.Enum): + r"""Output state. + + Values: + OUTPUT_STATE_UNSPECIFIED (0): + Unspecified output. + OUTPUT_STATE_OK (1): + Succeeded. + OUTPUT_STATE_CANCELLED (2): + Cancelled. + OUTPUT_STATE_FAILED (3): + Failed. + OUTPUT_STATE_ESCALATED (4): + Escalated. + OUTPUT_STATE_PENDING (5): + Pending. + """ + OUTPUT_STATE_UNSPECIFIED = 0 + OUTPUT_STATE_OK = 1 + OUTPUT_STATE_CANCELLED = 2 + OUTPUT_STATE_FAILED = 3 + OUTPUT_STATE_ESCALATED = 4 + OUTPUT_STATE_PENDING = 5 + + +class PlaybookInput(proto.Message): + r"""Input of the playbook. + + Attributes: + preceding_conversation_summary (str): + Optional. Summary string of the preceding + conversation for the child playbook invocation. + """ + + preceding_conversation_summary: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PlaybookOutput(proto.Message): + r"""Output of the playbook. + + Attributes: + execution_summary (str): + Optional. Summary string of the execution + result of the child playbook. + """ + + execution_summary: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Action(proto.Message): + r"""Action performed by end user or Dialogflow agent in the + conversation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_utterance (google.cloud.dialogflowcx_v3.types.UserUtterance): + Optional. Agent obtained a message from the + customer. + + This field is a member of `oneof`_ ``action``. + agent_utterance (google.cloud.dialogflowcx_v3.types.AgentUtterance): + Optional. Action performed by the agent as a + message. + + This field is a member of `oneof`_ ``action``. + tool_use (google.cloud.dialogflowcx_v3.types.ToolUse): + Optional. Action performed on behalf of the + agent by calling a plugin tool. + + This field is a member of `oneof`_ ``action``. + playbook_invocation (google.cloud.dialogflowcx_v3.types.PlaybookInvocation): + Optional. Action performed on behalf of the + agent by invoking a child playbook. + + This field is a member of `oneof`_ ``action``. + flow_invocation (google.cloud.dialogflowcx_v3.types.FlowInvocation): + Optional. Action performed on behalf of the + agent by invoking a CX flow. + + This field is a member of `oneof`_ ``action``. + playbook_transition (google.cloud.dialogflowcx_v3.types.PlaybookTransition): + Optional. Action performed on behalf of the + agent by transitioning to a target playbook. + + This field is a member of `oneof`_ ``action``. + flow_transition (google.cloud.dialogflowcx_v3.types.FlowTransition): + Optional. Action performed on behalf of the + agent by transitioning to a target CX flow. + + This field is a member of `oneof`_ ``action``. + """ + + user_utterance: "UserUtterance" = proto.Field( + proto.MESSAGE, + number=1, + oneof="action", + message="UserUtterance", + ) + agent_utterance: "AgentUtterance" = proto.Field( + proto.MESSAGE, + number=2, + oneof="action", + message="AgentUtterance", + ) + tool_use: "ToolUse" = proto.Field( + proto.MESSAGE, + number=3, + oneof="action", + message="ToolUse", + ) + playbook_invocation: "PlaybookInvocation" = proto.Field( + proto.MESSAGE, + number=4, + oneof="action", + message="PlaybookInvocation", + ) + flow_invocation: "FlowInvocation" = proto.Field( + proto.MESSAGE, + number=5, + oneof="action", + message="FlowInvocation", + ) + playbook_transition: "PlaybookTransition" = proto.Field( + proto.MESSAGE, + number=12, + oneof="action", + message="PlaybookTransition", + ) + flow_transition: "FlowTransition" = proto.Field( + proto.MESSAGE, + number=13, + oneof="action", + message="FlowTransition", + ) + + +class UserUtterance(proto.Message): + r"""UserUtterance represents one message sent by the customer. + + Attributes: + text (str): + Required. Message content in text. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AgentUtterance(proto.Message): + r"""AgentUtterance represents one message sent by the agent. + + Attributes: + text (str): + Required. Message content in text. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ToolUse(proto.Message): + r"""Stores metadata of the invocation of an action supported by a + tool. + + Attributes: + tool (str): + Required. The [tool][google.cloud.dialogflow.cx.v3.Tool] + that should be used. Format: + ``projects//locations//agents//tools/``. + display_name (str): + Output only. The display name of the tool. + action (str): + Optional. Name of the action to be called + during the tool use. + input_action_parameters (google.protobuf.struct_pb2.Struct): + Optional. A list of input parameters for the + action. + output_action_parameters (google.protobuf.struct_pb2.Struct): + Optional. A list of output parameters + generated by the action. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + action: str = proto.Field( + proto.STRING, + number=2, + ) + input_action_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + output_action_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +class PlaybookInvocation(proto.Message): + r"""Stores metadata of the invocation of a child playbook. + + Attributes: + playbook (str): + Required. The unique identifier of the playbook. Format: + ``projects//locations//agents//playbooks/``. + display_name (str): + Output only. The display name of the + playbook. + playbook_input (google.cloud.dialogflowcx_v3.types.PlaybookInput): + Optional. Input of the child playbook + invocation. + playbook_output (google.cloud.dialogflowcx_v3.types.PlaybookOutput): + Optional. Output of the child playbook + invocation. + playbook_state (google.cloud.dialogflowcx_v3.types.OutputState): + Required. Playbook invocation's output state. + """ + + playbook: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + playbook_input: "PlaybookInput" = proto.Field( + proto.MESSAGE, + number=2, + message="PlaybookInput", + ) + playbook_output: "PlaybookOutput" = proto.Field( + proto.MESSAGE, + number=3, + message="PlaybookOutput", + ) + playbook_state: "OutputState" = proto.Field( + proto.ENUM, + number=4, + enum="OutputState", + ) + + +class FlowInvocation(proto.Message): + r"""Stores metadata of the invocation of a CX flow. + + Attributes: + flow (str): + Required. The unique identifier of the flow. Format: + ``projects//locations//agents//flows/``. + display_name (str): + Output only. The display name of the flow. + flow_state (google.cloud.dialogflowcx_v3.types.OutputState): + Required. Flow invocation's output state. + """ + + flow: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + flow_state: "OutputState" = proto.Field( + proto.ENUM, + number=4, + enum="OutputState", + ) + + +class PlaybookTransition(proto.Message): + r"""Stores metadata of the transition to another target playbook. + Playbook transition actions exit the caller playbook and enter + the target playbook. + + Attributes: + playbook (str): + Required. The unique identifier of the playbook. Format: + ``projects//locations//agents//playbooks/``. + display_name (str): + Output only. The display name of the + playbook. + """ + + playbook: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class FlowTransition(proto.Message): + r"""Stores metadata of the transition to a target CX flow. Flow + transition actions exit the caller playbook and enter the child + flow. + + Attributes: + flow (str): + Required. The unique identifier of the flow. Format: + ``projects//locations//agents/``. + display_name (str): + Output only. The display name of the flow. + """ + + flow: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/webhook.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/webhook.py index 7c3d2830a971..5c4e5a0d2bc5 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/webhook.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/types/webhook.py @@ -99,9 +99,23 @@ class GenericWebService(proto.Message): The user name for HTTP Basic authentication. password (str): The password for HTTP Basic authentication. + secret_version_for_username_password (str): + Optional. The SecretManager secret version resource storing + the username:password pair for HTTP Basic authentication. + Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` request_headers (MutableMapping[str, str]): The HTTP request headers to send together with webhook requests. + secret_versions_for_request_headers (MutableMapping[str, google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService.SecretVersionHeaderValue]): + Optional. The HTTP request headers to send together with + webhook requests. Header values are stored in SecretManager + secret versions. + + When the same header name is specified in both + ``request_headers`` and + ``secret_versions_for_request_headers``, the value in + ``secret_versions_for_request_headers`` will be used. allowed_ca_certs (MutableSequence[bytes]): Optional. Specifies a list of allowed custom CA certificates (in DER format) for HTTPS verification. This overrides the @@ -128,6 +142,9 @@ class GenericWebService(proto.Message): `Diglogflow service agent `__. The generated token is sent in the Authorization header. + service_account_auth_config (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService.ServiceAccountAuthConfig): + Optional. Configuration for service account + authentication. webhook_type (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService.WebhookType): Optional. Type of the webhook. http_method (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService.HttpMethod): @@ -217,6 +234,22 @@ class HttpMethod(proto.Enum): PATCH = 6 OPTIONS = 7 + class SecretVersionHeaderValue(proto.Message): + r"""Represents the value of an HTTP header stored in a + SecretManager secret version. + + Attributes: + secret_version (str): + Required. The SecretManager secret version resource storing + the header value. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + """ + + secret_version: str = proto.Field( + proto.STRING, + number=1, + ) + class OAuthConfig(proto.Message): r"""Represents configuration of OAuth client credential flow for 3rd party API authentication. @@ -228,6 +261,11 @@ class OAuthConfig(proto.Message): client_secret (str): Optional. The client secret provided by the 3rd party platform. + secret_version_for_client_secret (str): + Optional. The name of the SecretManager secret version + resource storing the client secret. If this field is set, + the ``client_secret`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` token_endpoint (str): Required. The token endpoint provided by the 3rd party platform to exchange an access token. @@ -243,6 +281,10 @@ class OAuthConfig(proto.Message): proto.STRING, number=2, ) + secret_version_for_client_secret: str = proto.Field( + proto.STRING, + number=5, + ) token_endpoint: str = proto.Field( proto.STRING, number=3, @@ -252,6 +294,28 @@ class OAuthConfig(proto.Message): number=4, ) + class ServiceAccountAuthConfig(proto.Message): + r"""Configuration for authentication using a service account. + + Attributes: + service_account (str): + Required. The email address of the service account used to + authenticate the webhook call. Dialogflow uses this service + account to exchange an access token and the access token is + then sent in the ``Authorization`` header of the webhook + request. + + The service account must have the + ``roles/iam.serviceAccountTokenCreator`` role granted to the + `Dialogflow service + agent `__. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( proto.STRING, number=1, @@ -264,11 +328,23 @@ class OAuthConfig(proto.Message): proto.STRING, number=3, ) + secret_version_for_username_password: str = proto.Field( + proto.STRING, + number=19, + ) request_headers: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=4, ) + secret_versions_for_request_headers: MutableMapping[ + str, "Webhook.GenericWebService.SecretVersionHeaderValue" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=20, + message="Webhook.GenericWebService.SecretVersionHeaderValue", + ) allowed_ca_certs: MutableSequence[bytes] = proto.RepeatedField( proto.BYTES, number=5, @@ -283,6 +359,11 @@ class OAuthConfig(proto.Message): number=12, enum="Webhook.GenericWebService.ServiceAgentAuth", ) + service_account_auth_config: "Webhook.GenericWebService.ServiceAccountAuthConfig" = proto.Field( + proto.MESSAGE, + number=18, + message="Webhook.GenericWebService.ServiceAccountAuthConfig", + ) webhook_type: "Webhook.GenericWebService.WebhookType" = proto.Field( proto.ENUM, number=6, diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_async.py index e7dca7da58ae..4eeb6bdda316 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_async.py +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_async.py @@ -40,6 +40,7 @@ async def sample_create_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_sync.py index 2e4fadcd4c92..ee905975f17a 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_sync.py +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_create_agent_sync.py @@ -40,6 +40,7 @@ def sample_create_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_async.py index d050039b8dda..03716c429708 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_async.py +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_async.py @@ -40,6 +40,7 @@ async def sample_update_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_sync.py index 0ae33c51529c..1324c50c3a80 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_sync.py +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_agents_update_agent_sync.py @@ -40,6 +40,7 @@ def sample_update_agent(): # Initialize request argument(s) agent = dialogflowcx_v3.Agent() + agent.start_flow = "start_flow_value" agent.display_name = "display_name_value" agent.default_language_code = "default_language_code_value" agent.time_zone = "time_zone_value" diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_async.py new file mode 100644 index 000000000000..5c771d669411 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_CreateExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_create_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = await client.create_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_CreateExample_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_sync.py new file mode 100644 index 000000000000..6ece034dbdf0 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_create_example_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_CreateExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_create_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = client.create_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_CreateExample_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_async.py new file mode 100644 index 000000000000..64944ff6a0c3 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_DeleteExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_delete_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + await client.delete_example(request=request) + + +# [END dialogflow_v3_generated_Examples_DeleteExample_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_sync.py new file mode 100644 index 000000000000..53e0df3f403e --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_delete_example_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_DeleteExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_delete_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + client.delete_example(request=request) + + +# [END dialogflow_v3_generated_Examples_DeleteExample_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_async.py new file mode 100644 index 000000000000..b2b2160bc329 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_GetExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_get_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_GetExample_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_sync.py new file mode 100644 index 000000000000..072695acf38f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_get_example_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_GetExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_get_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = client.get_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_GetExample_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_async.py new file mode 100644 index 000000000000..baa4dde8a9be --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExamples +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_ListExamples_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_list_examples(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Examples_ListExamples_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_sync.py new file mode 100644 index 000000000000..c97067f96527 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_list_examples_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExamples +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_ListExamples_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_list_examples(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Examples_ListExamples_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_async.py new file mode 100644 index 000000000000..d74dbaa9c5d4 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_UpdateExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_update_example(): + # Create a client + client = dialogflowcx_v3.ExamplesAsyncClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = await client.update_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_UpdateExample_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_sync.py new file mode 100644 index 000000000000..6f18047d4e75 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_examples_update_example_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Examples_UpdateExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_update_example(): + # Create a client + client = dialogflowcx_v3.ExamplesClient() + + # Initialize request argument(s) + example = dialogflowcx_v3.Example() + example.actions.user_utterance.text = "text_value" + example.display_name = "display_name_value" + example.conversation_state = "OUTPUT_STATE_PENDING" + + request = dialogflowcx_v3.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = client.update_example(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Examples_UpdateExample_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_async.py new file mode 100644 index 000000000000..911edecec6b4 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_CreatePlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_create_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.CreatePlaybookRequest( + parent="parent_value", + playbook=playbook, + ) + + # Make the request + response = await client.create_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_CreatePlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_sync.py new file mode 100644 index 000000000000..8c949338aa59 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_CreatePlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_create_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.CreatePlaybookRequest( + parent="parent_value", + playbook=playbook, + ) + + # Make the request + response = client.create_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_CreatePlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_async.py new file mode 100644 index 000000000000..a810c3ced11a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_create_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_sync.py new file mode 100644 index 000000000000..41359910fb0c --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_create_playbook_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_create_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_async.py new file mode 100644 index 000000000000..12f17d523def --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_DeletePlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_delete_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookRequest( + name="name_value", + ) + + # Make the request + await client.delete_playbook(request=request) + + +# [END dialogflow_v3_generated_Playbooks_DeletePlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_sync.py new file mode 100644 index 000000000000..5f7c855cbd71 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_DeletePlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_delete_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookRequest( + name="name_value", + ) + + # Make the request + client.delete_playbook(request=request) + + +# [END dialogflow_v3_generated_Playbooks_DeletePlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_async.py new file mode 100644 index 000000000000..18e7c6ea0e9a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_delete_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_playbook_version(request=request) + + +# [END dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py new file mode 100644 index 000000000000..e1b33cc2a3fa --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_delete_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeletePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_playbook_version(request=request) + + +# [END dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_async.py new file mode 100644 index 000000000000..2ee788c1d4be --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ExportPlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_export_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ExportPlaybookRequest( + name="name_value", + ) + + # Make the request + operation = client.export_playbook(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ExportPlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_sync.py new file mode 100644 index 000000000000..965190201781 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_export_playbook_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ExportPlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_export_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ExportPlaybookRequest( + name="name_value", + ) + + # Make the request + operation = client.export_playbook(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ExportPlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_async.py new file mode 100644 index 000000000000..c0cbd5defeff --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_GetPlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_get_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookRequest( + name="name_value", + ) + + # Make the request + response = await client.get_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_GetPlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_sync.py new file mode 100644 index 000000000000..e9920c2b34df --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_GetPlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_get_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookRequest( + name="name_value", + ) + + # Make the request + response = client.get_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_GetPlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_async.py new file mode 100644 index 000000000000..2995b0f37968 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_GetPlaybookVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_get_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_GetPlaybookVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_sync.py new file mode 100644 index 000000000000..a3a15b23e897 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_get_playbook_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_GetPlaybookVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_get_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetPlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_GetPlaybookVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_async.py new file mode 100644 index 000000000000..e91cf1eac7f9 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ImportPlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_import_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ImportPlaybookRequest( + playbook_uri="playbook_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_playbook(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ImportPlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_sync.py new file mode 100644 index 000000000000..0a010002acf9 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_import_playbook_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportPlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ImportPlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_import_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ImportPlaybookRequest( + playbook_uri="playbook_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_playbook(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ImportPlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_async.py new file mode 100644 index 000000000000..54ed3062a234 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPlaybookVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ListPlaybookVersions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_list_playbook_versions(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybookVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbook_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ListPlaybookVersions_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py new file mode 100644 index 000000000000..196cf91dcf12 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPlaybookVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ListPlaybookVersions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_list_playbook_versions(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybookVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbook_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ListPlaybookVersions_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_async.py new file mode 100644 index 000000000000..ee1a8887c8d1 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPlaybooks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ListPlaybooks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_list_playbooks(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybooksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbooks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ListPlaybooks_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_sync.py new file mode 100644 index 000000000000..47112cc12e62 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_list_playbooks_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPlaybooks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_ListPlaybooks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_list_playbooks(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListPlaybooksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_playbooks(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Playbooks_ListPlaybooks_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_async.py new file mode 100644 index 000000000000..47aff60f170f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestorePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_restore_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestorePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py new file mode 100644 index 000000000000..1283a777e8b6 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestorePlaybookVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_restore_playbook_version(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestorePlaybookVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_playbook_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_async.py new file mode 100644 index 000000000000..b789cbd0f680 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdatePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_UpdatePlaybook_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_update_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksAsyncClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.UpdatePlaybookRequest( + playbook=playbook, + ) + + # Make the request + response = await client.update_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_UpdatePlaybook_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_sync.py new file mode 100644 index 000000000000..9a4e86843c19 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_playbooks_update_playbook_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdatePlaybook +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Playbooks_UpdatePlaybook_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_update_playbook(): + # Create a client + client = dialogflowcx_v3.PlaybooksClient() + + # Initialize request argument(s) + playbook = dialogflowcx_v3.Playbook() + playbook.display_name = "display_name_value" + playbook.goal = "goal_value" + + request = dialogflowcx_v3.UpdatePlaybookRequest( + playbook=playbook, + ) + + # Make the request + response = client.update_playbook(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Playbooks_UpdatePlaybook_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_async.py new file mode 100644 index 000000000000..184f9e272e29 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_CreateTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_create_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = await client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_CreateTool_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_sync.py new file mode 100644 index 000000000000..9a7870b340ca --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_CreateTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_create_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_CreateTool_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_async.py new file mode 100644 index 000000000000..1ea462754df3 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_CreateToolVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_create_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool_version = dialogflowcx_v3.ToolVersion() + tool_version.display_name = "display_name_value" + tool_version.tool.open_api_spec.text_schema = "text_schema_value" + tool_version.tool.display_name = "display_name_value" + tool_version.tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolVersionRequest( + parent="parent_value", + tool_version=tool_version, + ) + + # Make the request + response = await client.create_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_CreateToolVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_sync.py new file mode 100644 index 000000000000..eb53a73de739 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_create_tool_version_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_CreateToolVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_create_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool_version = dialogflowcx_v3.ToolVersion() + tool_version.display_name = "display_name_value" + tool_version.tool.open_api_spec.text_schema = "text_schema_value" + tool_version.tool.display_name = "display_name_value" + tool_version.tool.description = "description_value" + + request = dialogflowcx_v3.CreateToolVersionRequest( + parent="parent_value", + tool_version=tool_version, + ) + + # Make the request + response = client.create_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_CreateToolVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_async.py new file mode 100644 index 000000000000..56754498b11e --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_DeleteTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_delete_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + +# [END dialogflow_v3_generated_Tools_DeleteTool_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_sync.py new file mode 100644 index 000000000000..de1a5dfbb0fa --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_DeleteTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_delete_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + +# [END dialogflow_v3_generated_Tools_DeleteTool_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_async.py new file mode 100644 index 000000000000..2efd9326f235 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_DeleteToolVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_delete_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool_version(request=request) + + +# [END dialogflow_v3_generated_Tools_DeleteToolVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_sync.py new file mode 100644 index 000000000000..5b420accc2f2 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_delete_tool_version_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_DeleteToolVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_delete_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.DeleteToolVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_tool_version(request=request) + + +# [END dialogflow_v3_generated_Tools_DeleteToolVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_async.py new file mode 100644 index 000000000000..6871f9739793 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_GetTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_get_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_GetTool_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_sync.py new file mode 100644 index 000000000000..044829e174ce --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_GetTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_get_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_GetTool_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_async.py new file mode 100644 index 000000000000..c297c2d4ba72 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_GetToolVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_get_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_GetToolVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_sync.py new file mode 100644 index 000000000000..3b2d7e877297 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_get_tool_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_GetToolVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_get_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.GetToolVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_GetToolVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_async.py new file mode 100644 index 000000000000..7fd1bbc0617f --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListToolVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_ListToolVersions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_list_tool_versions(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tool_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Tools_ListToolVersions_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_sync.py new file mode 100644 index 000000000000..af60a7ede662 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tool_versions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListToolVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_ListToolVersions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_list_tool_versions(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tool_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Tools_ListToolVersions_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_async.py new file mode 100644 index 000000000000..d14cb0bfc3ce --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_ListTools_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_list_tools(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Tools_ListTools_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_sync.py new file mode 100644 index 000000000000..7acc25f548df --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_list_tools_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_ListTools_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_list_tools(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v3_generated_Tools_ListTools_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_async.py new file mode 100644 index 000000000000..1bc035625b35 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_RestoreToolVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_restore_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestoreToolVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_RestoreToolVersion_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_sync.py new file mode 100644 index 000000000000..cc1b2de4634a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_restore_tool_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreToolVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_RestoreToolVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_restore_tool_version(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + request = dialogflowcx_v3.RestoreToolVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_tool_version(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_RestoreToolVersion_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_async.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_async.py new file mode 100644 index 000000000000..f5f1acbc901a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_UpdateTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +async def sample_update_tool(): + # Create a client + client = dialogflowcx_v3.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_UpdateTool_async] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_sync.py b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_sync.py new file mode 100644 index 000000000000..f2df70fbfc99 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/dialogflow_v3_generated_tools_update_tool_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dialogflow-cx + + +# [START dialogflow_v3_generated_Tools_UpdateTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dialogflowcx_v3 + + +def sample_update_tool(): + # Create a client + client = dialogflowcx_v3.ToolsClient() + + # Initialize request argument(s) + tool = dialogflowcx_v3.Tool() + tool.open_api_spec.text_schema = "text_schema_value" + tool.display_name = "display_name_value" + tool.description = "description_value" + + request = dialogflowcx_v3.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v3_generated_Tools_UpdateTool_sync] diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json index fd25be45407d..df2bdfea2a59 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json @@ -64,12 +64,12 @@ "regionTag": "dialogflow_v3_generated_Agents_CreateAgent_async", "segments": [ { - "end": 57, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 58, "start": 27, "type": "SHORT" }, @@ -79,18 +79,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], @@ -148,12 +148,12 @@ "regionTag": "dialogflow_v3_generated_Agents_CreateAgent_sync", "segments": [ { - "end": 57, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 58, "start": 27, "type": "SHORT" }, @@ -163,18 +163,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], @@ -1346,12 +1346,12 @@ "regionTag": "dialogflow_v3_generated_Agents_UpdateAgent_async", "segments": [ { - "end": 56, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1361,18 +1361,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -1430,12 +1430,12 @@ "regionTag": "dialogflow_v3_generated_Agents_UpdateAgent_sync", "segments": [ { - "end": 56, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1445,18 +1445,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -4997,30 +4997,30 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", - "shortName": "ExperimentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient", + "shortName": "ExamplesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.create_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient.create_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.CreateExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "CreateExperiment" + "shortName": "CreateExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateExampleRequest" }, { "name": "parent", "type": "str" }, { - "name": "experiment", - "type": "google.cloud.dialogflowcx_v3.types.Experiment" + "name": "example", + "type": "google.cloud.dialogflowcx_v3.types.Example" }, { "name": "retry", @@ -5035,22 +5035,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "create_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "create_example" }, - "description": "Sample for CreateExperiment", - "file": "dialogflow_v3_generated_experiments_create_experiment_async.py", + "description": "Sample for CreateExample", + "file": "dialogflow_v3_generated_examples_create_example_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_CreateExperiment_async", + "regionTag": "dialogflow_v3_generated_Examples_CreateExample_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -5060,51 +5060,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_create_experiment_async.py" + "title": "dialogflow_v3_generated_examples_create_example_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", - "shortName": "ExperimentsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient", + "shortName": "ExamplesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.create_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient.create_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.CreateExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "CreateExperiment" + "shortName": "CreateExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateExampleRequest" }, { "name": "parent", "type": "str" }, { - "name": "experiment", - "type": "google.cloud.dialogflowcx_v3.types.Experiment" + "name": "example", + "type": "google.cloud.dialogflowcx_v3.types.Example" }, { "name": "retry", @@ -5119,22 +5119,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "create_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "create_example" }, - "description": "Sample for CreateExperiment", - "file": "dialogflow_v3_generated_experiments_create_experiment_sync.py", + "description": "Sample for CreateExample", + "file": "dialogflow_v3_generated_examples_create_example_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_CreateExperiment_sync", + "regionTag": "dialogflow_v3_generated_Examples_CreateExample_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -5144,44 +5144,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_create_experiment_sync.py" + "title": "dialogflow_v3_generated_examples_create_example_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", - "shortName": "ExperimentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient", + "shortName": "ExamplesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.delete_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient.delete_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.DeleteExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "DeleteExperiment" + "shortName": "DeleteExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteExampleRequest" }, { "name": "name", @@ -5200,13 +5200,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_experiment" + "shortName": "delete_example" }, - "description": "Sample for DeleteExperiment", - "file": "dialogflow_v3_generated_experiments_delete_experiment_async.py", + "description": "Sample for DeleteExample", + "file": "dialogflow_v3_generated_examples_delete_example_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_DeleteExperiment_async", + "regionTag": "dialogflow_v3_generated_Examples_DeleteExample_async", "segments": [ { "end": 49, @@ -5237,28 +5237,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_delete_experiment_async.py" + "title": "dialogflow_v3_generated_examples_delete_example_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", - "shortName": "ExperimentsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient", + "shortName": "ExamplesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.delete_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient.delete_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.DeleteExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "DeleteExperiment" + "shortName": "DeleteExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteExampleRequest" }, { "name": "name", @@ -5277,13 +5277,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_experiment" + "shortName": "delete_example" }, - "description": "Sample for DeleteExperiment", - "file": "dialogflow_v3_generated_experiments_delete_experiment_sync.py", + "description": "Sample for DeleteExample", + "file": "dialogflow_v3_generated_examples_delete_example_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_DeleteExperiment_sync", + "regionTag": "dialogflow_v3_generated_Examples_DeleteExample_sync", "segments": [ { "end": 49, @@ -5314,29 +5314,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_delete_experiment_sync.py" + "title": "dialogflow_v3_generated_examples_delete_example_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", - "shortName": "ExperimentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient", + "shortName": "ExamplesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.get_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient.get_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.GetExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.GetExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "GetExperiment" + "shortName": "GetExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetExampleRequest" }, { "name": "name", @@ -5355,14 +5355,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "get_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "get_example" }, - "description": "Sample for GetExperiment", - "file": "dialogflow_v3_generated_experiments_get_experiment_async.py", + "description": "Sample for GetExample", + "file": "dialogflow_v3_generated_examples_get_example_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_GetExperiment_async", + "regionTag": "dialogflow_v3_generated_Examples_GetExample_async", "segments": [ { "end": 51, @@ -5395,28 +5395,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_get_experiment_async.py" + "title": "dialogflow_v3_generated_examples_get_example_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", - "shortName": "ExperimentsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient", + "shortName": "ExamplesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.get_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient.get_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.GetExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.GetExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "GetExperiment" + "shortName": "GetExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetExampleRequest" }, { "name": "name", @@ -5435,14 +5435,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "get_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "get_example" }, - "description": "Sample for GetExperiment", - "file": "dialogflow_v3_generated_experiments_get_experiment_sync.py", + "description": "Sample for GetExample", + "file": "dialogflow_v3_generated_examples_get_example_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_GetExperiment_sync", + "regionTag": "dialogflow_v3_generated_Examples_GetExample_sync", "segments": [ { "end": 51, @@ -5475,29 +5475,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_get_experiment_sync.py" + "title": "dialogflow_v3_generated_examples_get_example_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", - "shortName": "ExperimentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient", + "shortName": "ExamplesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.list_experiments", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient.list_examples", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.ListExperiments", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.ListExamples", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "ListExperiments" + "shortName": "ListExamples" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListExperimentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListExamplesRequest" }, { "name": "parent", @@ -5516,14 +5516,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsAsyncPager", - "shortName": "list_experiments" + "resultType": "google.cloud.dialogflowcx_v3.services.examples.pagers.ListExamplesAsyncPager", + "shortName": "list_examples" }, - "description": "Sample for ListExperiments", - "file": "dialogflow_v3_generated_experiments_list_experiments_async.py", + "description": "Sample for ListExamples", + "file": "dialogflow_v3_generated_examples_list_examples_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_ListExperiments_async", + "regionTag": "dialogflow_v3_generated_Examples_ListExamples_async", "segments": [ { "end": 52, @@ -5556,28 +5556,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_list_experiments_async.py" + "title": "dialogflow_v3_generated_examples_list_examples_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", - "shortName": "ExperimentsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient", + "shortName": "ExamplesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.list_experiments", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient.list_examples", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.ListExperiments", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.ListExamples", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "ListExperiments" + "shortName": "ListExamples" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListExperimentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListExamplesRequest" }, { "name": "parent", @@ -5596,14 +5596,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsPager", - "shortName": "list_experiments" + "resultType": "google.cloud.dialogflowcx_v3.services.examples.pagers.ListExamplesPager", + "shortName": "list_examples" }, - "description": "Sample for ListExperiments", - "file": "dialogflow_v3_generated_experiments_list_experiments_sync.py", + "description": "Sample for ListExamples", + "file": "dialogflow_v3_generated_examples_list_examples_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_ListExperiments_sync", + "regionTag": "dialogflow_v3_generated_Examples_ListExamples_sync", "segments": [ { "end": 52, @@ -5636,33 +5636,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_list_experiments_sync.py" + "title": "dialogflow_v3_generated_examples_list_examples_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", - "shortName": "ExperimentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient", + "shortName": "ExamplesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.start_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesAsyncClient.update_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StartExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.UpdateExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "StartExperiment" + "shortName": "UpdateExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.StartExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateExampleRequest" }, { - "name": "name", - "type": "str" + "name": "example", + "type": "google.cloud.dialogflowcx_v3.types.Example" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5677,22 +5681,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "start_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "update_example" }, - "description": "Sample for StartExperiment", - "file": "dialogflow_v3_generated_experiments_start_experiment_async.py", + "description": "Sample for UpdateExample", + "file": "dialogflow_v3_generated_examples_update_example_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_StartExperiment_async", + "regionTag": "dialogflow_v3_generated_Examples_UpdateExample_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -5702,47 +5706,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_start_experiment_async.py" + "title": "dialogflow_v3_generated_examples_update_example_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", - "shortName": "ExperimentsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient", + "shortName": "ExamplesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.start_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExamplesClient.update_example", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StartExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Examples.UpdateExample", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments", - "shortName": "Experiments" + "fullName": "google.cloud.dialogflow.cx.v3.Examples", + "shortName": "Examples" }, - "shortName": "StartExperiment" + "shortName": "UpdateExample" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.StartExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateExampleRequest" }, { - "name": "name", - "type": "str" + "name": "example", + "type": "google.cloud.dialogflowcx_v3.types.Example" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5757,22 +5765,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "start_experiment" + "resultType": "google.cloud.dialogflowcx_v3.types.Example", + "shortName": "update_example" }, - "description": "Sample for StartExperiment", - "file": "dialogflow_v3_generated_experiments_start_experiment_sync.py", + "description": "Sample for UpdateExample", + "file": "dialogflow_v3_generated_examples_update_example_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_StartExperiment_sync", + "regionTag": "dialogflow_v3_generated_Examples_UpdateExample_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -5782,22 +5790,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_start_experiment_sync.py" + "title": "dialogflow_v3_generated_examples_update_example_sync.py" }, { "canonical": true, @@ -5807,24 +5815,28 @@ "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.stop_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.create_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StopExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Experiments", "shortName": "Experiments" }, - "shortName": "StopExperiment" + "shortName": "CreateExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.StopExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateExperimentRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "experiment", + "type": "google.cloud.dialogflowcx_v3.types.Experiment" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -5839,21 +5851,21 @@ } ], "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "stop_experiment" + "shortName": "create_experiment" }, - "description": "Sample for StopExperiment", - "file": "dialogflow_v3_generated_experiments_stop_experiment_async.py", + "description": "Sample for CreateExperiment", + "file": "dialogflow_v3_generated_experiments_create_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_StopExperiment_async", + "regionTag": "dialogflow_v3_generated_Experiments_CreateExperiment_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5863,22 +5875,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_stop_experiment_async.py" + "title": "dialogflow_v3_generated_experiments_create_experiment_async.py" }, { "canonical": true, @@ -5887,24 +5899,28 @@ "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.stop_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.create_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StopExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Experiments", "shortName": "Experiments" }, - "shortName": "StopExperiment" + "shortName": "CreateExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.StopExperimentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateExperimentRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "experiment", + "type": "google.cloud.dialogflowcx_v3.types.Experiment" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -5919,21 +5935,21 @@ } ], "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "stop_experiment" + "shortName": "create_experiment" }, - "description": "Sample for StopExperiment", - "file": "dialogflow_v3_generated_experiments_stop_experiment_sync.py", + "description": "Sample for CreateExperiment", + "file": "dialogflow_v3_generated_experiments_create_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_StopExperiment_sync", + "regionTag": "dialogflow_v3_generated_Experiments_CreateExperiment_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5943,22 +5959,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_stop_experiment_sync.py" + "title": "dialogflow_v3_generated_experiments_create_experiment_sync.py" }, { "canonical": true, @@ -5968,27 +5984,23 @@ "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.update_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.delete_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Experiments", "shortName": "Experiments" }, - "shortName": "UpdateExperiment" + "shortName": "DeleteExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest" - }, - { - "name": "experiment", - "type": "google.cloud.dialogflowcx_v3.types.Experiment" + "type": "google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -6003,22 +6015,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "update_experiment" + "shortName": "delete_experiment" }, - "description": "Sample for UpdateExperiment", - "file": "dialogflow_v3_generated_experiments_update_experiment_async.py", + "description": "Sample for DeleteExperiment", + "file": "dialogflow_v3_generated_experiments_delete_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_UpdateExperiment_async", + "regionTag": "dialogflow_v3_generated_Experiments_DeleteExperiment_async", "segments": [ { - "end": 54, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 49, "start": 27, "type": "SHORT" }, @@ -6028,22 +6039,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_update_experiment_async.py" + "title": "dialogflow_v3_generated_experiments_delete_experiment_async.py" }, { "canonical": true, @@ -6052,27 +6061,23 @@ "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.update_experiment", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.delete_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Experiments", "shortName": "Experiments" }, - "shortName": "UpdateExperiment" + "shortName": "DeleteExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest" - }, - { - "name": "experiment", - "type": "google.cloud.dialogflowcx_v3.types.Experiment" + "type": "google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -6087,22 +6092,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", - "shortName": "update_experiment" + "shortName": "delete_experiment" }, - "description": "Sample for UpdateExperiment", - "file": "dialogflow_v3_generated_experiments_update_experiment_sync.py", + "description": "Sample for DeleteExperiment", + "file": "dialogflow_v3_generated_experiments_delete_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Experiments_UpdateExperiment_sync", + "regionTag": "dialogflow_v3_generated_Experiments_DeleteExperiment_sync", "segments": [ { - "end": 54, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 49, "start": 27, "type": "SHORT" }, @@ -6112,53 +6116,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_experiments_update_experiment_sync.py" + "title": "dialogflow_v3_generated_experiments_delete_experiment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", - "shortName": "FlowsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", + "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.create_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.get_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.CreateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.GetExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "CreateFlow" + "shortName": "GetExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetExperimentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "flow", - "type": "google.cloud.dialogflowcx_v3.types.Flow" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6172,22 +6170,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "create_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "get_experiment" }, - "description": "Sample for CreateFlow", - "file": "dialogflow_v3_generated_flows_create_flow_async.py", + "description": "Sample for GetExperiment", + "file": "dialogflow_v3_generated_experiments_get_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_CreateFlow_async", + "regionTag": "dialogflow_v3_generated_Experiments_GetExperiment_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6197,52 +6195,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_create_flow_async.py" + "title": "dialogflow_v3_generated_experiments_get_experiment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", - "shortName": "FlowsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", + "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.create_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.get_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.CreateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.GetExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "CreateFlow" + "shortName": "GetExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetExperimentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "flow", - "type": "google.cloud.dialogflowcx_v3.types.Flow" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6256,22 +6250,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "create_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "get_experiment" }, - "description": "Sample for CreateFlow", - "file": "dialogflow_v3_generated_flows_create_flow_sync.py", + "description": "Sample for GetExperiment", + "file": "dialogflow_v3_generated_experiments_get_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_CreateFlow_sync", + "regionTag": "dialogflow_v3_generated_Experiments_GetExperiment_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6281,47 +6275,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_create_flow_sync.py" + "title": "dialogflow_v3_generated_experiments_get_experiment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", - "shortName": "FlowsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", + "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.delete_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.list_experiments", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.DeleteFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.ListExperiments", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "DeleteFlow" + "shortName": "ListExperiments" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListExperimentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -6337,21 +6331,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_flow" + "resultType": "google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsAsyncPager", + "shortName": "list_experiments" }, - "description": "Sample for DeleteFlow", - "file": "dialogflow_v3_generated_flows_delete_flow_async.py", + "description": "Sample for ListExperiments", + "file": "dialogflow_v3_generated_experiments_list_experiments_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_DeleteFlow_async", + "regionTag": "dialogflow_v3_generated_Experiments_ListExperiments_async", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6366,39 +6361,41 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_delete_flow_async.py" + "title": "dialogflow_v3_generated_experiments_list_experiments_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", - "shortName": "FlowsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", + "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.delete_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.list_experiments", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.DeleteFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.ListExperiments", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "DeleteFlow" + "shortName": "ListExperiments" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListExperimentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -6414,21 +6411,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_flow" + "resultType": "google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsPager", + "shortName": "list_experiments" }, - "description": "Sample for DeleteFlow", - "file": "dialogflow_v3_generated_flows_delete_flow_sync.py", + "description": "Sample for ListExperiments", + "file": "dialogflow_v3_generated_experiments_list_experiments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_DeleteFlow_sync", + "regionTag": "dialogflow_v3_generated_Experiments_ListExperiments_sync", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6443,37 +6441,43 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_delete_flow_sync.py" + "title": "dialogflow_v3_generated_experiments_list_experiments_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", - "shortName": "FlowsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", + "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.export_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.start_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ExportFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StartExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "ExportFlow" + "shortName": "StartExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.StartExperimentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -6488,22 +6492,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "start_experiment" }, - "description": "Sample for ExportFlow", - "file": "dialogflow_v3_generated_flows_export_flow_async.py", + "description": "Sample for StartExperiment", + "file": "dialogflow_v3_generated_experiments_start_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ExportFlow_async", + "regionTag": "dialogflow_v3_generated_Experiments_StartExperiment_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6518,38 +6522,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_export_flow_async.py" + "title": "dialogflow_v3_generated_experiments_start_experiment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", - "shortName": "FlowsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", + "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.export_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.start_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ExportFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StartExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "ExportFlow" + "shortName": "StartExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.StartExperimentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -6564,22 +6572,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "start_experiment" }, - "description": "Sample for ExportFlow", - "file": "dialogflow_v3_generated_flows_export_flow_sync.py", + "description": "Sample for StartExperiment", + "file": "dialogflow_v3_generated_experiments_start_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ExportFlow_sync", + "regionTag": "dialogflow_v3_generated_Experiments_StartExperiment_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6594,39 +6602,39 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_export_flow_sync.py" + "title": "dialogflow_v3_generated_experiments_start_experiment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", - "shortName": "FlowsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", + "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.get_flow_validation_result", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.stop_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StopExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "GetFlowValidationResult" + "shortName": "StopExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest" + "type": "google.cloud.dialogflowcx_v3.types.StopExperimentRequest" }, { "name": "name", @@ -6645,14 +6653,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", - "shortName": "get_flow_validation_result" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "stop_experiment" }, - "description": "Sample for GetFlowValidationResult", - "file": "dialogflow_v3_generated_flows_get_flow_validation_result_async.py", + "description": "Sample for StopExperiment", + "file": "dialogflow_v3_generated_experiments_stop_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_GetFlowValidationResult_async", + "regionTag": "dialogflow_v3_generated_Experiments_StopExperiment_async", "segments": [ { "end": 51, @@ -6685,28 +6693,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_get_flow_validation_result_async.py" + "title": "dialogflow_v3_generated_experiments_stop_experiment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", - "shortName": "FlowsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", + "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.get_flow_validation_result", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.stop_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.StopExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "GetFlowValidationResult" + "shortName": "StopExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest" + "type": "google.cloud.dialogflowcx_v3.types.StopExperimentRequest" }, { "name": "name", @@ -6725,14 +6733,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", - "shortName": "get_flow_validation_result" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "stop_experiment" }, - "description": "Sample for GetFlowValidationResult", - "file": "dialogflow_v3_generated_flows_get_flow_validation_result_sync.py", + "description": "Sample for StopExperiment", + "file": "dialogflow_v3_generated_experiments_stop_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_GetFlowValidationResult_sync", + "regionTag": "dialogflow_v3_generated_Experiments_StopExperiment_sync", "segments": [ { "end": 51, @@ -6765,33 +6773,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_get_flow_validation_result_sync.py" + "title": "dialogflow_v3_generated_experiments_stop_experiment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", - "shortName": "FlowsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient", + "shortName": "ExperimentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.get_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsAsyncClient.update_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "GetFlow" + "shortName": "UpdateExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest" }, { - "name": "name", - "type": "str" + "name": "experiment", + "type": "google.cloud.dialogflowcx_v3.types.Experiment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -6806,22 +6818,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "get_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "update_experiment" }, - "description": "Sample for GetFlow", - "file": "dialogflow_v3_generated_flows_get_flow_async.py", + "description": "Sample for UpdateExperiment", + "file": "dialogflow_v3_generated_experiments_update_experiment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_GetFlow_async", + "regionTag": "dialogflow_v3_generated_Experiments_UpdateExperiment_async", "segments": [ { - "end": 51, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 54, "start": 27, "type": "SHORT" }, @@ -6831,47 +6843,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_get_flow_async.py" + "title": "dialogflow_v3_generated_experiments_update_experiment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", - "shortName": "FlowsClient" + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient", + "shortName": "ExperimentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.get_flow", + "fullName": "google.cloud.dialogflowcx_v3.ExperimentsClient.update_experiment", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows", - "shortName": "Flows" + "fullName": "google.cloud.dialogflow.cx.v3.Experiments", + "shortName": "Experiments" }, - "shortName": "GetFlow" + "shortName": "UpdateExperiment" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest" }, { - "name": "name", - "type": "str" + "name": "experiment", + "type": "google.cloud.dialogflowcx_v3.types.Experiment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -6886,22 +6902,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "get_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Experiment", + "shortName": "update_experiment" }, - "description": "Sample for GetFlow", - "file": "dialogflow_v3_generated_flows_get_flow_sync.py", + "description": "Sample for UpdateExperiment", + "file": "dialogflow_v3_generated_experiments_update_experiment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_GetFlow_sync", + "regionTag": "dialogflow_v3_generated_Experiments_UpdateExperiment_sync", "segments": [ { - "end": 51, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 54, "start": 27, "type": "SHORT" }, @@ -6911,22 +6927,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_get_flow_sync.py" + "title": "dialogflow_v3_generated_experiments_update_experiment_sync.py" }, { "canonical": true, @@ -6936,19 +6952,27 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.import_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.create_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ImportFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.CreateFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ImportFlow" + "shortName": "CreateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateFlowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "flow", + "type": "google.cloud.dialogflowcx_v3.types.Flow" }, { "name": "retry", @@ -6963,22 +6987,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "create_flow" }, - "description": "Sample for ImportFlow", - "file": "dialogflow_v3_generated_flows_import_flow_async.py", + "description": "Sample for CreateFlow", + "file": "dialogflow_v3_generated_flows_create_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ImportFlow_async", + "regionTag": "dialogflow_v3_generated_Flows_CreateFlow_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6988,22 +7012,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_import_flow_async.py" + "title": "dialogflow_v3_generated_flows_create_flow_async.py" }, { "canonical": true, @@ -7012,19 +7036,27 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.import_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.create_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ImportFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.CreateFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ImportFlow" + "shortName": "CreateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateFlowRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "flow", + "type": "google.cloud.dialogflowcx_v3.types.Flow" }, { "name": "retry", @@ -7039,22 +7071,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "create_flow" }, - "description": "Sample for ImportFlow", - "file": "dialogflow_v3_generated_flows_import_flow_sync.py", + "description": "Sample for CreateFlow", + "file": "dialogflow_v3_generated_flows_create_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ImportFlow_sync", + "regionTag": "dialogflow_v3_generated_Flows_CreateFlow_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -7064,22 +7096,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_import_flow_sync.py" + "title": "dialogflow_v3_generated_flows_create_flow_sync.py" }, { "canonical": true, @@ -7089,22 +7121,22 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.list_flows", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.delete_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ListFlows", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.DeleteFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ListFlows" + "shortName": "DeleteFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListFlowsRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteFlowRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -7120,22 +7152,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsAsyncPager", - "shortName": "list_flows" + "shortName": "delete_flow" }, - "description": "Sample for ListFlows", - "file": "dialogflow_v3_generated_flows_list_flows_async.py", + "description": "Sample for DeleteFlow", + "file": "dialogflow_v3_generated_flows_delete_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ListFlows_async", + "regionTag": "dialogflow_v3_generated_Flows_DeleteFlow_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -7150,17 +7181,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_list_flows_async.py" + "title": "dialogflow_v3_generated_flows_delete_flow_async.py" }, { "canonical": true, @@ -7169,22 +7198,22 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.list_flows", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.delete_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ListFlows", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.DeleteFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ListFlows" + "shortName": "DeleteFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListFlowsRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteFlowRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -7200,22 +7229,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsPager", - "shortName": "list_flows" + "shortName": "delete_flow" }, - "description": "Sample for ListFlows", - "file": "dialogflow_v3_generated_flows_list_flows_sync.py", + "description": "Sample for DeleteFlow", + "file": "dialogflow_v3_generated_flows_delete_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ListFlows_sync", + "regionTag": "dialogflow_v3_generated_Flows_DeleteFlow_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -7230,17 +7258,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_list_flows_sync.py" + "title": "dialogflow_v3_generated_flows_delete_flow_sync.py" }, { "canonical": true, @@ -7250,23 +7276,19 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.train_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.export_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.TrainFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ExportFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "TrainFlow" + "shortName": "ExportFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.TrainFlowRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.ExportFlowRequest" }, { "name": "retry", @@ -7282,13 +7304,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_flow" + "shortName": "export_flow" }, - "description": "Sample for TrainFlow", - "file": "dialogflow_v3_generated_flows_train_flow_async.py", + "description": "Sample for ExportFlow", + "file": "dialogflow_v3_generated_flows_export_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_TrainFlow_async", + "regionTag": "dialogflow_v3_generated_Flows_ExportFlow_async", "segments": [ { "end": 55, @@ -7321,7 +7343,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_train_flow_async.py" + "title": "dialogflow_v3_generated_flows_export_flow_async.py" }, { "canonical": true, @@ -7330,23 +7352,19 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.train_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.export_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.TrainFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ExportFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "TrainFlow" + "shortName": "ExportFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.TrainFlowRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.ExportFlowRequest" }, { "name": "retry", @@ -7362,13 +7380,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "train_flow" + "shortName": "export_flow" }, - "description": "Sample for TrainFlow", - "file": "dialogflow_v3_generated_flows_train_flow_sync.py", + "description": "Sample for ExportFlow", + "file": "dialogflow_v3_generated_flows_export_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_TrainFlow_sync", + "regionTag": "dialogflow_v3_generated_Flows_ExportFlow_sync", "segments": [ { "end": 55, @@ -7401,7 +7419,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_train_flow_sync.py" + "title": "dialogflow_v3_generated_flows_export_flow_sync.py" }, { "canonical": true, @@ -7411,27 +7429,23 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.update_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.get_flow_validation_result", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.UpdateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "UpdateFlow" + "shortName": "GetFlowValidationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest" }, { - "name": "flow", - "type": "google.cloud.dialogflowcx_v3.types.Flow" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -7446,22 +7460,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "update_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", + "shortName": "get_flow_validation_result" }, - "description": "Sample for UpdateFlow", - "file": "dialogflow_v3_generated_flows_update_flow_async.py", + "description": "Sample for GetFlowValidationResult", + "file": "dialogflow_v3_generated_flows_get_flow_validation_result_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_UpdateFlow_async", + "regionTag": "dialogflow_v3_generated_Flows_GetFlowValidationResult_async", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -7471,22 +7485,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_update_flow_async.py" + "title": "dialogflow_v3_generated_flows_get_flow_validation_result_async.py" }, { "canonical": true, @@ -7495,27 +7509,23 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.update_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.get_flow_validation_result", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.UpdateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "UpdateFlow" + "shortName": "GetFlowValidationResult" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateFlowRequest" - }, - { - "name": "flow", - "type": "google.cloud.dialogflowcx_v3.types.Flow" + "type": "google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -7530,22 +7540,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Flow", - "shortName": "update_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", + "shortName": "get_flow_validation_result" }, - "description": "Sample for UpdateFlow", - "file": "dialogflow_v3_generated_flows_update_flow_sync.py", + "description": "Sample for GetFlowValidationResult", + "file": "dialogflow_v3_generated_flows_get_flow_validation_result_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_UpdateFlow_sync", + "regionTag": "dialogflow_v3_generated_Flows_GetFlowValidationResult_sync", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -7555,22 +7565,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_update_flow_sync.py" + "title": "dialogflow_v3_generated_flows_get_flow_validation_result_sync.py" }, { "canonical": true, @@ -7580,19 +7590,23 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.validate_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.get_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ValidateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ValidateFlow" + "shortName": "GetFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ValidateFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetFlowRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -7607,14 +7621,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", - "shortName": "validate_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "get_flow" }, - "description": "Sample for ValidateFlow", - "file": "dialogflow_v3_generated_flows_validate_flow_async.py", + "description": "Sample for GetFlow", + "file": "dialogflow_v3_generated_flows_get_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ValidateFlow_async", + "regionTag": "dialogflow_v3_generated_Flows_GetFlow_async", "segments": [ { "end": 51, @@ -7647,7 +7661,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_validate_flow_async.py" + "title": "dialogflow_v3_generated_flows_get_flow_async.py" }, { "canonical": true, @@ -7656,19 +7670,23 @@ "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.validate_flow", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.get_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Flows.ValidateFlow", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.GetFlow", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Flows", "shortName": "Flows" }, - "shortName": "ValidateFlow" + "shortName": "GetFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ValidateFlowRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetFlowRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -7683,14 +7701,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", - "shortName": "validate_flow" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "get_flow" }, - "description": "Sample for ValidateFlow", - "file": "dialogflow_v3_generated_flows_validate_flow_sync.py", + "description": "Sample for GetFlow", + "file": "dialogflow_v3_generated_flows_get_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Flows_ValidateFlow_sync", + "regionTag": "dialogflow_v3_generated_Flows_GetFlow_sync", "segments": [ { "end": 51, @@ -7723,37 +7741,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_flows_validate_flow_sync.py" + "title": "dialogflow_v3_generated_flows_get_flow_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", + "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.create_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.import_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.CreateGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ImportFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "CreateGenerator" + "shortName": "ImportFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateGeneratorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "generator", - "type": "google.cloud.dialogflowcx_v3.types.Generator" + "type": "google.cloud.dialogflowcx_v3.types.ImportFlowRequest" }, { "name": "retry", @@ -7768,14 +7778,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "create_generator" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_flow" }, - "description": "Sample for CreateGenerator", - "file": "dialogflow_v3_generated_generators_create_generator_async.py", + "description": "Sample for ImportFlow", + "file": "dialogflow_v3_generated_flows_import_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_CreateGenerator_async", + "regionTag": "dialogflow_v3_generated_Flows_ImportFlow_async", "segments": [ { "end": 56, @@ -7793,13 +7803,13 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { @@ -7808,36 +7818,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_create_generator_async.py" + "title": "dialogflow_v3_generated_flows_import_flow_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", + "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.create_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.import_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.CreateGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ImportFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "CreateGenerator" + "shortName": "ImportFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateGeneratorRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "generator", - "type": "google.cloud.dialogflowcx_v3.types.Generator" + "type": "google.cloud.dialogflowcx_v3.types.ImportFlowRequest" }, { "name": "retry", @@ -7852,14 +7854,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "create_generator" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_flow" }, - "description": "Sample for CreateGenerator", - "file": "dialogflow_v3_generated_generators_create_generator_sync.py", + "description": "Sample for ImportFlow", + "file": "dialogflow_v3_generated_flows_import_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_CreateGenerator_sync", + "regionTag": "dialogflow_v3_generated_Flows_ImportFlow_sync", "segments": [ { "end": 56, @@ -7877,13 +7879,13 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { @@ -7892,32 +7894,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_create_generator_sync.py" + "title": "dialogflow_v3_generated_flows_import_flow_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", + "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.delete_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.list_flows", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.DeleteGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ListFlows", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "DeleteGenerator" + "shortName": "ListFlows" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteGeneratorRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListFlowsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -7933,21 +7935,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_generator" + "resultType": "google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsAsyncPager", + "shortName": "list_flows" }, - "description": "Sample for DeleteGenerator", - "file": "dialogflow_v3_generated_generators_delete_generator_async.py", + "description": "Sample for ListFlows", + "file": "dialogflow_v3_generated_flows_list_flows_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_DeleteGenerator_async", + "regionTag": "dialogflow_v3_generated_Flows_ListFlows_async", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7962,39 +7965,41 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_delete_generator_async.py" + "title": "dialogflow_v3_generated_flows_list_flows_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", + "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.delete_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.list_flows", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.DeleteGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ListFlows", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "DeleteGenerator" + "shortName": "ListFlows" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteGeneratorRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListFlowsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -8010,21 +8015,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_generator" + "resultType": "google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsPager", + "shortName": "list_flows" }, - "description": "Sample for DeleteGenerator", - "file": "dialogflow_v3_generated_generators_delete_generator_sync.py", + "description": "Sample for ListFlows", + "file": "dialogflow_v3_generated_flows_list_flows_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_DeleteGenerator_sync", + "regionTag": "dialogflow_v3_generated_Flows_ListFlows_sync", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8039,37 +8045,39 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_delete_generator_sync.py" + "title": "dialogflow_v3_generated_flows_list_flows_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", + "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.get_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.train_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.GetGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.TrainFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "GetGenerator" + "shortName": "TrainFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetGeneratorRequest" + "type": "google.cloud.dialogflowcx_v3.types.TrainFlowRequest" }, { "name": "name", @@ -8088,22 +8096,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "get_generator" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "train_flow" }, - "description": "Sample for GetGenerator", - "file": "dialogflow_v3_generated_generators_get_generator_async.py", + "description": "Sample for TrainFlow", + "file": "dialogflow_v3_generated_flows_train_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_GetGenerator_async", + "regionTag": "dialogflow_v3_generated_Flows_TrainFlow_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -8118,38 +8126,38 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_get_generator_async.py" + "title": "dialogflow_v3_generated_flows_train_flow_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", + "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.get_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.train_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.GetGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.TrainFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "GetGenerator" + "shortName": "TrainFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetGeneratorRequest" + "type": "google.cloud.dialogflowcx_v3.types.TrainFlowRequest" }, { "name": "name", @@ -8168,22 +8176,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "get_generator" + "resultType": "google.api_core.operation.Operation", + "shortName": "train_flow" }, - "description": "Sample for GetGenerator", - "file": "dialogflow_v3_generated_generators_get_generator_sync.py", + "description": "Sample for TrainFlow", + "file": "dialogflow_v3_generated_flows_train_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_GetGenerator_sync", + "regionTag": "dialogflow_v3_generated_Flows_TrainFlow_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -8198,43 +8206,47 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_get_generator_sync.py" + "title": "dialogflow_v3_generated_flows_train_flow_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", + "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.list_generators", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.update_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.ListGenerators", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.UpdateFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "ListGenerators" + "shortName": "UpdateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListGeneratorsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateFlowRequest" }, { - "name": "parent", - "type": "str" + "name": "flow", + "type": "google.cloud.dialogflowcx_v3.types.Flow" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8249,22 +8261,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.generators.pagers.ListGeneratorsAsyncPager", - "shortName": "list_generators" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "update_flow" }, - "description": "Sample for ListGenerators", - "file": "dialogflow_v3_generated_generators_list_generators_async.py", + "description": "Sample for UpdateFlow", + "file": "dialogflow_v3_generated_flows_update_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_ListGenerators_async", + "regionTag": "dialogflow_v3_generated_Flows_UpdateFlow_async", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -8274,47 +8286,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_list_generators_async.py" + "title": "dialogflow_v3_generated_flows_update_flow_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", + "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.list_generators", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.update_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.ListGenerators", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.UpdateFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "ListGenerators" + "shortName": "UpdateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListGeneratorsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateFlowRequest" }, { - "name": "parent", - "type": "str" + "name": "flow", + "type": "google.cloud.dialogflowcx_v3.types.Flow" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8329,22 +8345,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.generators.pagers.ListGeneratorsPager", - "shortName": "list_generators" + "resultType": "google.cloud.dialogflowcx_v3.types.Flow", + "shortName": "update_flow" }, - "description": "Sample for ListGenerators", - "file": "dialogflow_v3_generated_generators_list_generators_sync.py", + "description": "Sample for UpdateFlow", + "file": "dialogflow_v3_generated_flows_update_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_ListGenerators_sync", + "regionTag": "dialogflow_v3_generated_Flows_UpdateFlow_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -8354,52 +8370,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_list_generators_sync.py" + "title": "dialogflow_v3_generated_flows_update_flow_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient", + "shortName": "FlowsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.update_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsAsyncClient.validate_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.UpdateGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ValidateFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "UpdateGenerator" + "shortName": "ValidateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateGeneratorRequest" - }, - { - "name": "generator", - "type": "google.cloud.dialogflowcx_v3.types.Generator" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.dialogflowcx_v3.types.ValidateFlowRequest" }, { "name": "retry", @@ -8414,22 +8422,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "update_generator" + "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", + "shortName": "validate_flow" }, - "description": "Sample for UpdateGenerator", - "file": "dialogflow_v3_generated_generators_update_generator_async.py", + "description": "Sample for ValidateFlow", + "file": "dialogflow_v3_generated_flows_validate_flow_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_UpdateGenerator_async", + "regionTag": "dialogflow_v3_generated_Flows_ValidateFlow_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8439,51 +8447,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_update_generator_async.py" + "title": "dialogflow_v3_generated_flows_validate_flow_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient", + "shortName": "FlowsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.update_generator", + "fullName": "google.cloud.dialogflowcx_v3.FlowsClient.validate_flow", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators.UpdateGenerator", + "fullName": "google.cloud.dialogflow.cx.v3.Flows.ValidateFlow", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.cx.v3.Flows", + "shortName": "Flows" }, - "shortName": "UpdateGenerator" + "shortName": "ValidateFlow" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateGeneratorRequest" - }, - { - "name": "generator", - "type": "google.cloud.dialogflowcx_v3.types.Generator" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.dialogflowcx_v3.types.ValidateFlowRequest" }, { "name": "retry", @@ -8498,22 +8498,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Generator", - "shortName": "update_generator" + "resultType": "google.cloud.dialogflowcx_v3.types.FlowValidationResult", + "shortName": "validate_flow" }, - "description": "Sample for UpdateGenerator", - "file": "dialogflow_v3_generated_generators_update_generator_sync.py", + "description": "Sample for ValidateFlow", + "file": "dialogflow_v3_generated_flows_validate_flow_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Generators_UpdateGenerator_sync", + "regionTag": "dialogflow_v3_generated_Flows_ValidateFlow_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8523,52 +8523,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_generators_update_generator_sync.py" + "title": "dialogflow_v3_generated_flows_validate_flow_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.create_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.create_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.CreateIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.CreateGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "CreateIntent" + "shortName": "CreateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateGeneratorRequest" }, { "name": "parent", "type": "str" }, { - "name": "intent", - "type": "google.cloud.dialogflowcx_v3.types.Intent" + "name": "generator", + "type": "google.cloud.dialogflowcx_v3.types.Generator" }, { "name": "retry", @@ -8583,22 +8583,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "create_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "create_generator" }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v3_generated_intents_create_intent_async.py", + "description": "Sample for CreateGenerator", + "file": "dialogflow_v3_generated_generators_create_generator_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_CreateIntent_async", + "regionTag": "dialogflow_v3_generated_Generators_CreateGenerator_async", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -8608,51 +8608,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_create_intent_async.py" + "title": "dialogflow_v3_generated_generators_create_generator_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", + "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.create_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.create_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.CreateIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.CreateGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "CreateIntent" + "shortName": "CreateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateGeneratorRequest" }, { "name": "parent", "type": "str" }, { - "name": "intent", - "type": "google.cloud.dialogflowcx_v3.types.Intent" + "name": "generator", + "type": "google.cloud.dialogflowcx_v3.types.Generator" }, { "name": "retry", @@ -8667,22 +8667,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "create_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "create_generator" }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v3_generated_intents_create_intent_sync.py", + "description": "Sample for CreateGenerator", + "file": "dialogflow_v3_generated_generators_create_generator_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_CreateIntent_sync", + "regionTag": "dialogflow_v3_generated_Generators_CreateGenerator_sync", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -8692,44 +8692,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_create_intent_sync.py" + "title": "dialogflow_v3_generated_generators_create_generator_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.delete_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.delete_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.DeleteIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.DeleteGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "DeleteIntent" + "shortName": "DeleteGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteGeneratorRequest" }, { "name": "name", @@ -8748,13 +8748,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_intent" + "shortName": "delete_generator" }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v3_generated_intents_delete_intent_async.py", + "description": "Sample for DeleteGenerator", + "file": "dialogflow_v3_generated_generators_delete_generator_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_DeleteIntent_async", + "regionTag": "dialogflow_v3_generated_Generators_DeleteGenerator_async", "segments": [ { "end": 49, @@ -8785,28 +8785,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_delete_intent_async.py" + "title": "dialogflow_v3_generated_generators_delete_generator_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", + "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.delete_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.delete_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.DeleteIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.DeleteGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "DeleteIntent" + "shortName": "DeleteGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteGeneratorRequest" }, { "name": "name", @@ -8825,13 +8825,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_intent" + "shortName": "delete_generator" }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v3_generated_intents_delete_intent_sync.py", + "description": "Sample for DeleteGenerator", + "file": "dialogflow_v3_generated_generators_delete_generator_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_DeleteIntent_sync", + "regionTag": "dialogflow_v3_generated_Generators_DeleteGenerator_sync", "segments": [ { "end": 49, @@ -8862,29 +8862,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_delete_intent_sync.py" + "title": "dialogflow_v3_generated_generators_delete_generator_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.export_intents", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.get_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ExportIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.GetGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "ExportIntents" + "shortName": "GetGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetGeneratorRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -8899,22 +8903,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "get_generator" }, - "description": "Sample for ExportIntents", - "file": "dialogflow_v3_generated_intents_export_intents_async.py", + "description": "Sample for GetGenerator", + "file": "dialogflow_v3_generated_generators_get_generator_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ExportIntents_async", + "regionTag": "dialogflow_v3_generated_Generators_GetGenerator_async", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8924,43 +8928,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_export_intents_async.py" + "title": "dialogflow_v3_generated_generators_get_generator_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", + "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.export_intents", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.get_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ExportIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.GetGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "ExportIntents" + "shortName": "GetGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetGeneratorRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -8975,22 +8983,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "get_generator" }, - "description": "Sample for ExportIntents", - "file": "dialogflow_v3_generated_intents_export_intents_sync.py", + "description": "Sample for GetGenerator", + "file": "dialogflow_v3_generated_generators_get_generator_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ExportIntents_sync", + "regionTag": "dialogflow_v3_generated_Generators_GetGenerator_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9000,47 +9008,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_export_intents_sync.py" + "title": "dialogflow_v3_generated_generators_get_generator_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.get_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.list_generators", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.GetIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.ListGenerators", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "GetIntent" + "shortName": "ListGenerators" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListGeneratorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -9056,22 +9064,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "get_intent" + "resultType": "google.cloud.dialogflowcx_v3.services.generators.pagers.ListGeneratorsAsyncPager", + "shortName": "list_generators" }, - "description": "Sample for GetIntent", - "file": "dialogflow_v3_generated_intents_get_intent_async.py", + "description": "Sample for ListGenerators", + "file": "dialogflow_v3_generated_generators_list_generators_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_GetIntent_async", + "regionTag": "dialogflow_v3_generated_Generators_ListGenerators_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9091,36 +9099,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_get_intent_async.py" + "title": "dialogflow_v3_generated_generators_list_generators_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", + "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.get_intent", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.list_generators", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.GetIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.ListGenerators", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "GetIntent" + "shortName": "ListGenerators" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListGeneratorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -9136,22 +9144,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "get_intent" + "resultType": "google.cloud.dialogflowcx_v3.services.generators.pagers.ListGeneratorsPager", + "shortName": "list_generators" }, - "description": "Sample for GetIntent", - "file": "dialogflow_v3_generated_intents_get_intent_sync.py", + "description": "Sample for ListGenerators", + "file": "dialogflow_v3_generated_generators_list_generators_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_GetIntent_sync", + "regionTag": "dialogflow_v3_generated_Generators_ListGenerators_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9171,34 +9179,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_get_intent_sync.py" + "title": "dialogflow_v3_generated_generators_list_generators_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.import_intents", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsAsyncClient.update_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ImportIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.UpdateGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "ImportIntents" + "shortName": "UpdateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateGeneratorRequest" + }, + { + "name": "generator", + "type": "google.cloud.dialogflowcx_v3.types.Generator" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9213,22 +9229,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "update_generator" }, - "description": "Sample for ImportIntents", - "file": "dialogflow_v3_generated_intents_import_intents_async.py", + "description": "Sample for UpdateGenerator", + "file": "dialogflow_v3_generated_generators_update_generator_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ImportIntents_async", + "regionTag": "dialogflow_v3_generated_Generators_UpdateGenerator_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9238,43 +9254,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_import_intents_async.py" + "title": "dialogflow_v3_generated_generators_update_generator_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient", + "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.import_intents", + "fullName": "google.cloud.dialogflowcx_v3.GeneratorsClient.update_generator", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ImportIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Generators.UpdateGenerator", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.cx.v3.Generators", + "shortName": "Generators" }, - "shortName": "ImportIntents" + "shortName": "UpdateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateGeneratorRequest" + }, + { + "name": "generator", + "type": "google.cloud.dialogflowcx_v3.types.Generator" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9289,22 +9313,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Generator", + "shortName": "update_generator" }, - "description": "Sample for ImportIntents", - "file": "dialogflow_v3_generated_intents_import_intents_sync.py", + "description": "Sample for UpdateGenerator", + "file": "dialogflow_v3_generated_generators_update_generator_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ImportIntents_sync", + "regionTag": "dialogflow_v3_generated_Generators_UpdateGenerator_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9314,22 +9338,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_import_intents_sync.py" + "title": "dialogflow_v3_generated_generators_update_generator_sync.py" }, { "canonical": true, @@ -9339,24 +9363,28 @@ "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.list_intents", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.create_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ListIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.CreateIntent", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Intents", "shortName": "Intents" }, - "shortName": "ListIntents" + "shortName": "CreateIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateIntentRequest" }, { "name": "parent", "type": "str" }, + { + "name": "intent", + "type": "google.cloud.dialogflowcx_v3.types.Intent" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9370,22 +9398,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsAsyncPager", - "shortName": "list_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "create_intent" }, - "description": "Sample for ListIntents", - "file": "dialogflow_v3_generated_intents_list_intents_async.py", + "description": "Sample for CreateIntent", + "file": "dialogflow_v3_generated_intents_create_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ListIntents_async", + "regionTag": "dialogflow_v3_generated_Intents_CreateIntent_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9395,22 +9423,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_list_intents_async.py" + "title": "dialogflow_v3_generated_intents_create_intent_async.py" }, { "canonical": true, @@ -9419,24 +9447,28 @@ "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.list_intents", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.create_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.ListIntents", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.CreateIntent", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Intents", "shortName": "Intents" }, - "shortName": "ListIntents" + "shortName": "CreateIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListIntentsRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateIntentRequest" }, { "name": "parent", "type": "str" }, + { + "name": "intent", + "type": "google.cloud.dialogflowcx_v3.types.Intent" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9450,22 +9482,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsPager", - "shortName": "list_intents" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "create_intent" }, - "description": "Sample for ListIntents", - "file": "dialogflow_v3_generated_intents_list_intents_sync.py", + "description": "Sample for CreateIntent", + "file": "dialogflow_v3_generated_intents_create_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_ListIntents_sync", + "regionTag": "dialogflow_v3_generated_Intents_CreateIntent_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9475,22 +9507,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_list_intents_sync.py" + "title": "dialogflow_v3_generated_intents_create_intent_sync.py" }, { "canonical": true, @@ -9500,27 +9532,23 @@ "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.update_intent", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.delete_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.UpdateIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.DeleteIntent", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Intents", "shortName": "Intents" }, - "shortName": "UpdateIntent" + "shortName": "DeleteIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflowcx_v3.types.Intent" + "type": "google.cloud.dialogflowcx_v3.types.DeleteIntentRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -9535,22 +9563,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "update_intent" + "shortName": "delete_intent" }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v3_generated_intents_update_intent_async.py", + "description": "Sample for DeleteIntent", + "file": "dialogflow_v3_generated_intents_delete_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_UpdateIntent_async", + "regionTag": "dialogflow_v3_generated_Intents_DeleteIntent_async", "segments": [ { - "end": 54, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 49, "start": 27, "type": "SHORT" }, @@ -9560,22 +9587,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_update_intent_async.py" + "title": "dialogflow_v3_generated_intents_delete_intent_async.py" }, { "canonical": true, @@ -9584,27 +9609,23 @@ "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.update_intent", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.delete_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Intents.UpdateIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.DeleteIntent", "service": { "fullName": "google.cloud.dialogflow.cx.v3.Intents", "shortName": "Intents" }, - "shortName": "UpdateIntent" + "shortName": "DeleteIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflowcx_v3.types.Intent" + "type": "google.cloud.dialogflowcx_v3.types.DeleteIntentRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -9619,22 +9640,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Intent", - "shortName": "update_intent" + "shortName": "delete_intent" }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v3_generated_intents_update_intent_sync.py", + "description": "Sample for DeleteIntent", + "file": "dialogflow_v3_generated_intents_delete_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Intents_UpdateIntent_sync", + "regionTag": "dialogflow_v3_generated_Intents_DeleteIntent_sync", "segments": [ { - "end": 54, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 49, "start": 27, "type": "SHORT" }, @@ -9644,52 +9664,42 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_intents_update_intent_sync.py" + "title": "dialogflow_v3_generated_intents_delete_intent_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", - "shortName": "PagesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.create_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.export_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.CreatePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ExportIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "CreatePage" + "shortName": "ExportIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreatePageRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "page", - "type": "google.cloud.dialogflowcx_v3.types.Page" + "type": "google.cloud.dialogflowcx_v3.types.ExportIntentsRequest" }, { "name": "retry", @@ -9704,22 +9714,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "create_page" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_intents" }, - "description": "Sample for CreatePage", - "file": "dialogflow_v3_generated_pages_create_page_async.py", + "description": "Sample for ExportIntents", + "file": "dialogflow_v3_generated_intents_export_intents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_CreatePage_async", + "regionTag": "dialogflow_v3_generated_Intents_ExportIntents_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -9729,51 +9739,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_create_page_async.py" + "title": "dialogflow_v3_generated_intents_export_intents_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesClient", - "shortName": "PagesClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", + "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesClient.create_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.export_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.CreatePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ExportIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "CreatePage" + "shortName": "ExportIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreatePageRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "page", - "type": "google.cloud.dialogflowcx_v3.types.Page" + "type": "google.cloud.dialogflowcx_v3.types.ExportIntentsRequest" }, { "name": "retry", @@ -9788,22 +9790,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "create_page" + "resultType": "google.api_core.operation.Operation", + "shortName": "export_intents" }, - "description": "Sample for CreatePage", - "file": "dialogflow_v3_generated_pages_create_page_sync.py", + "description": "Sample for ExportIntents", + "file": "dialogflow_v3_generated_intents_export_intents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_CreatePage_sync", + "regionTag": "dialogflow_v3_generated_Intents_ExportIntents_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -9813,44 +9815,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_create_page_sync.py" + "title": "dialogflow_v3_generated_intents_export_intents_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", - "shortName": "PagesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.delete_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.get_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.DeletePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.GetIntent", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "DeletePage" + "shortName": "GetIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeletePageRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetIntentRequest" }, { "name": "name", @@ -9869,21 +9871,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_page" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "get_intent" }, - "description": "Sample for DeletePage", - "file": "dialogflow_v3_generated_pages_delete_page_async.py", + "description": "Sample for GetIntent", + "file": "dialogflow_v3_generated_intents_get_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_DeletePage_async", + "regionTag": "dialogflow_v3_generated_Intents_GetIntent_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9898,36 +9901,38 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_delete_page_async.py" + "title": "dialogflow_v3_generated_intents_get_intent_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesClient", - "shortName": "PagesClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", + "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesClient.delete_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.get_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.DeletePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.GetIntent", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "DeletePage" + "shortName": "GetIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeletePageRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetIntentRequest" }, { "name": "name", @@ -9946,21 +9951,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_page" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "get_intent" }, - "description": "Sample for DeletePage", - "file": "dialogflow_v3_generated_pages_delete_page_sync.py", + "description": "Sample for GetIntent", + "file": "dialogflow_v3_generated_intents_get_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_DeletePage_sync", + "regionTag": "dialogflow_v3_generated_Intents_GetIntent_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9975,41 +9981,39 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_delete_page_sync.py" + "title": "dialogflow_v3_generated_intents_get_intent_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", - "shortName": "PagesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.get_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.import_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.GetPage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ImportIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "GetPage" + "shortName": "ImportIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetPageRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.ImportIntentsRequest" }, { "name": "retry", @@ -10024,22 +10028,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "get_page" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_intents" }, - "description": "Sample for GetPage", - "file": "dialogflow_v3_generated_pages_get_page_async.py", + "description": "Sample for ImportIntents", + "file": "dialogflow_v3_generated_intents_import_intents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_GetPage_async", + "regionTag": "dialogflow_v3_generated_Intents_ImportIntents_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -10049,47 +10053,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_get_page_async.py" + "title": "dialogflow_v3_generated_intents_import_intents_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesClient", - "shortName": "PagesClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", + "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesClient.get_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.import_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.GetPage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ImportIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "GetPage" + "shortName": "ImportIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetPageRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.ImportIntentsRequest" }, { "name": "retry", @@ -10104,22 +10104,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "get_page" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_intents" }, - "description": "Sample for GetPage", - "file": "dialogflow_v3_generated_pages_get_page_sync.py", + "description": "Sample for ImportIntents", + "file": "dialogflow_v3_generated_intents_import_intents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_GetPage_sync", + "regionTag": "dialogflow_v3_generated_Intents_ImportIntents_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -10129,44 +10129,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_get_page_sync.py" + "title": "dialogflow_v3_generated_intents_import_intents_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", - "shortName": "PagesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.list_pages", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.list_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.ListPages", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ListIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "ListPages" + "shortName": "ListIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListPagesRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListIntentsRequest" }, { "name": "parent", @@ -10185,14 +10185,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesAsyncPager", - "shortName": "list_pages" + "resultType": "google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsAsyncPager", + "shortName": "list_intents" }, - "description": "Sample for ListPages", - "file": "dialogflow_v3_generated_pages_list_pages_async.py", + "description": "Sample for ListIntents", + "file": "dialogflow_v3_generated_intents_list_intents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_ListPages_async", + "regionTag": "dialogflow_v3_generated_Intents_ListIntents_async", "segments": [ { "end": 52, @@ -10225,28 +10225,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_list_pages_async.py" + "title": "dialogflow_v3_generated_intents_list_intents_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesClient", - "shortName": "PagesClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", + "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesClient.list_pages", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.list_intents", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.ListPages", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.ListIntents", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "ListPages" + "shortName": "ListIntents" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListPagesRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListIntentsRequest" }, { "name": "parent", @@ -10265,14 +10265,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesPager", - "shortName": "list_pages" + "resultType": "google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsPager", + "shortName": "list_intents" }, - "description": "Sample for ListPages", - "file": "dialogflow_v3_generated_pages_list_pages_sync.py", + "description": "Sample for ListIntents", + "file": "dialogflow_v3_generated_intents_list_intents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_ListPages_sync", + "regionTag": "dialogflow_v3_generated_Intents_ListIntents_sync", "segments": [ { "end": 52, @@ -10305,33 +10305,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_list_pages_sync.py" + "title": "dialogflow_v3_generated_intents_list_intents_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", - "shortName": "PagesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.update_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsAsyncClient.update_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.UpdatePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.UpdateIntent", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "UpdatePage" + "shortName": "UpdateIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdatePageRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateIntentRequest" }, { - "name": "page", - "type": "google.cloud.dialogflowcx_v3.types.Page" + "name": "intent", + "type": "google.cloud.dialogflowcx_v3.types.Intent" }, { "name": "update_mask", @@ -10350,14 +10350,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "update_page" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "update_intent" }, - "description": "Sample for UpdatePage", - "file": "dialogflow_v3_generated_pages_update_page_async.py", + "description": "Sample for UpdateIntent", + "file": "dialogflow_v3_generated_intents_update_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_UpdatePage_async", + "regionTag": "dialogflow_v3_generated_Intents_UpdateIntent_async", "segments": [ { "end": 54, @@ -10390,32 +10390,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_update_page_async.py" + "title": "dialogflow_v3_generated_intents_update_intent_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.PagesClient", - "shortName": "PagesClient" + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient", + "shortName": "IntentsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.PagesClient.update_page", + "fullName": "google.cloud.dialogflowcx_v3.IntentsClient.update_intent", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages.UpdatePage", + "fullName": "google.cloud.dialogflow.cx.v3.Intents.UpdateIntent", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Pages", - "shortName": "Pages" + "fullName": "google.cloud.dialogflow.cx.v3.Intents", + "shortName": "Intents" }, - "shortName": "UpdatePage" + "shortName": "UpdateIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdatePageRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateIntentRequest" }, { - "name": "page", - "type": "google.cloud.dialogflowcx_v3.types.Page" + "name": "intent", + "type": "google.cloud.dialogflowcx_v3.types.Intent" }, { "name": "update_mask", @@ -10434,14 +10434,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.Page", - "shortName": "update_page" + "resultType": "google.cloud.dialogflowcx_v3.types.Intent", + "shortName": "update_intent" }, - "description": "Sample for UpdatePage", - "file": "dialogflow_v3_generated_pages_update_page_sync.py", + "description": "Sample for UpdateIntent", + "file": "dialogflow_v3_generated_intents_update_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Pages_UpdatePage_sync", + "regionTag": "dialogflow_v3_generated_Intents_UpdateIntent_sync", "segments": [ { "end": 54, @@ -10474,37 +10474,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_pages_update_page_sync.py" + "title": "dialogflow_v3_generated_intents_update_intent_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", - "shortName": "SecuritySettingsServiceAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", + "shortName": "PagesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.create_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.create_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.CreateSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.CreatePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "CreateSecuritySettings" + "shortName": "CreatePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePageRequest" }, { "name": "parent", "type": "str" }, { - "name": "security_settings", - "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + "name": "page", + "type": "google.cloud.dialogflowcx_v3.types.Page" }, { "name": "retry", @@ -10519,22 +10519,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "create_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "create_page" }, - "description": "Sample for CreateSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_create_security_settings_async.py", + "description": "Sample for CreatePage", + "file": "dialogflow_v3_generated_pages_create_page_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_CreateSecuritySettings_async", + "regionTag": "dialogflow_v3_generated_Pages_CreatePage_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10544,51 +10544,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_create_security_settings_async.py" + "title": "dialogflow_v3_generated_pages_create_page_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", - "shortName": "SecuritySettingsServiceClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesClient", + "shortName": "PagesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.create_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesClient.create_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.CreateSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.CreatePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "CreateSecuritySettings" + "shortName": "CreatePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePageRequest" }, { "name": "parent", "type": "str" }, { - "name": "security_settings", - "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + "name": "page", + "type": "google.cloud.dialogflowcx_v3.types.Page" }, { "name": "retry", @@ -10603,22 +10603,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "create_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "create_page" }, - "description": "Sample for CreateSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_create_security_settings_sync.py", + "description": "Sample for CreatePage", + "file": "dialogflow_v3_generated_pages_create_page_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_CreateSecuritySettings_sync", + "regionTag": "dialogflow_v3_generated_Pages_CreatePage_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10628,44 +10628,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_create_security_settings_sync.py" + "title": "dialogflow_v3_generated_pages_create_page_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", - "shortName": "SecuritySettingsServiceAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", + "shortName": "PagesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.delete_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.delete_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.DeleteSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.DeletePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "DeleteSecuritySettings" + "shortName": "DeletePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePageRequest" }, { "name": "name", @@ -10684,13 +10684,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_security_settings" + "shortName": "delete_page" }, - "description": "Sample for DeleteSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_delete_security_settings_async.py", + "description": "Sample for DeletePage", + "file": "dialogflow_v3_generated_pages_delete_page_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_DeleteSecuritySettings_async", + "regionTag": "dialogflow_v3_generated_Pages_DeletePage_async", "segments": [ { "end": 49, @@ -10721,28 +10721,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_delete_security_settings_async.py" + "title": "dialogflow_v3_generated_pages_delete_page_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", - "shortName": "SecuritySettingsServiceClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesClient", + "shortName": "PagesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.delete_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesClient.delete_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.DeleteSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.DeletePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "DeleteSecuritySettings" + "shortName": "DeletePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePageRequest" }, { "name": "name", @@ -10761,13 +10761,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_security_settings" + "shortName": "delete_page" }, - "description": "Sample for DeleteSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_delete_security_settings_sync.py", + "description": "Sample for DeletePage", + "file": "dialogflow_v3_generated_pages_delete_page_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_DeleteSecuritySettings_sync", + "regionTag": "dialogflow_v3_generated_Pages_DeletePage_sync", "segments": [ { "end": 49, @@ -10798,29 +10798,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_delete_security_settings_sync.py" + "title": "dialogflow_v3_generated_pages_delete_page_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", - "shortName": "SecuritySettingsServiceAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", + "shortName": "PagesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.get_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.get_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.GetPage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "GetSecuritySettings" + "shortName": "GetPage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPageRequest" }, { "name": "name", @@ -10839,14 +10839,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "get_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "get_page" }, - "description": "Sample for GetSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_get_security_settings_async.py", + "description": "Sample for GetPage", + "file": "dialogflow_v3_generated_pages_get_page_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_GetSecuritySettings_async", + "regionTag": "dialogflow_v3_generated_Pages_GetPage_async", "segments": [ { "end": 51, @@ -10879,28 +10879,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_get_security_settings_async.py" + "title": "dialogflow_v3_generated_pages_get_page_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", - "shortName": "SecuritySettingsServiceClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesClient", + "shortName": "PagesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.get_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesClient.get_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.GetPage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "GetSecuritySettings" + "shortName": "GetPage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPageRequest" }, { "name": "name", @@ -10919,14 +10919,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "get_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "get_page" }, - "description": "Sample for GetSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_get_security_settings_sync.py", + "description": "Sample for GetPage", + "file": "dialogflow_v3_generated_pages_get_page_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_GetSecuritySettings_sync", + "regionTag": "dialogflow_v3_generated_Pages_GetPage_sync", "segments": [ { "end": 51, @@ -10959,29 +10959,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_get_security_settings_sync.py" + "title": "dialogflow_v3_generated_pages_get_page_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", - "shortName": "SecuritySettingsServiceAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", + "shortName": "PagesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.list_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.list_pages", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.ListSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.ListPages", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "ListSecuritySettings" + "shortName": "ListPages" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListPagesRequest" }, { "name": "parent", @@ -11000,14 +11000,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager", - "shortName": "list_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesAsyncPager", + "shortName": "list_pages" }, - "description": "Sample for ListSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_list_security_settings_async.py", + "description": "Sample for ListPages", + "file": "dialogflow_v3_generated_pages_list_pages_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_ListSecuritySettings_async", + "regionTag": "dialogflow_v3_generated_Pages_ListPages_async", "segments": [ { "end": 52, @@ -11040,28 +11040,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_list_security_settings_async.py" + "title": "dialogflow_v3_generated_pages_list_pages_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", - "shortName": "SecuritySettingsServiceClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesClient", + "shortName": "PagesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.list_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesClient.list_pages", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.ListSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.ListPages", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "ListSecuritySettings" + "shortName": "ListPages" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListPagesRequest" }, { "name": "parent", @@ -11080,14 +11080,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsPager", - "shortName": "list_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesPager", + "shortName": "list_pages" }, - "description": "Sample for ListSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_list_security_settings_sync.py", + "description": "Sample for ListPages", + "file": "dialogflow_v3_generated_pages_list_pages_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_ListSecuritySettings_sync", + "regionTag": "dialogflow_v3_generated_Pages_ListPages_sync", "segments": [ { "end": 52, @@ -11120,33 +11120,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_list_security_settings_sync.py" + "title": "dialogflow_v3_generated_pages_list_pages_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", - "shortName": "SecuritySettingsServiceAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient", + "shortName": "PagesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.update_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesAsyncClient.update_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.UpdatePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "UpdateSecuritySettings" + "shortName": "UpdatePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdatePageRequest" }, { - "name": "security_settings", - "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + "name": "page", + "type": "google.cloud.dialogflowcx_v3.types.Page" }, { "name": "update_mask", @@ -11165,22 +11165,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "update_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "update_page" }, - "description": "Sample for UpdateSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_update_security_settings_async.py", + "description": "Sample for UpdatePage", + "file": "dialogflow_v3_generated_pages_update_page_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_UpdateSecuritySettings_async", + "regionTag": "dialogflow_v3_generated_Pages_UpdatePage_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -11190,47 +11190,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_update_security_settings_async.py" + "title": "dialogflow_v3_generated_pages_update_page_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", - "shortName": "SecuritySettingsServiceClient" + "fullName": "google.cloud.dialogflowcx_v3.PagesClient", + "shortName": "PagesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.update_security_settings", + "fullName": "google.cloud.dialogflowcx_v3.PagesClient.update_page", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings", + "fullName": "google.cloud.dialogflow.cx.v3.Pages.UpdatePage", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", - "shortName": "SecuritySettingsService" + "fullName": "google.cloud.dialogflow.cx.v3.Pages", + "shortName": "Pages" }, - "shortName": "UpdateSecuritySettings" + "shortName": "UpdatePage" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdatePageRequest" }, { - "name": "security_settings", - "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + "name": "page", + "type": "google.cloud.dialogflowcx_v3.types.Page" }, { "name": "update_mask", @@ -11249,22 +11249,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", - "shortName": "update_security_settings" + "resultType": "google.cloud.dialogflowcx_v3.types.Page", + "shortName": "update_page" }, - "description": "Sample for UpdateSecuritySettings", - "file": "dialogflow_v3_generated_security_settings_service_update_security_settings_sync.py", + "description": "Sample for UpdatePage", + "file": "dialogflow_v3_generated_pages_update_page_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SecuritySettingsService_UpdateSecuritySettings_sync", + "regionTag": "dialogflow_v3_generated_Pages_UpdatePage_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -11274,52 +11274,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_security_settings_service_update_security_settings_sync.py" + "title": "dialogflow_v3_generated_pages_update_page_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.create_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.create_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "CreateSessionEntityType" + "shortName": "CreatePlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePlaybookVersionRequest" }, { "name": "parent", "type": "str" }, { - "name": "session_entity_type", - "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + "name": "playbook_version", + "type": "google.cloud.dialogflowcx_v3.types.PlaybookVersion" }, { "name": "retry", @@ -11334,22 +11334,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "create_session_entity_type" + "resultType": "google.cloud.dialogflowcx_v3.types.PlaybookVersion", + "shortName": "create_playbook_version" }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_async.py", + "description": "Sample for CreatePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_create_playbook_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_CreateSessionEntityType_async", + "regionTag": "dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_async", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11359,51 +11359,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_async.py" + "title": "dialogflow_v3_generated_playbooks_create_playbook_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.create_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.create_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "CreateSessionEntityType" + "shortName": "CreatePlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePlaybookVersionRequest" }, { "name": "parent", "type": "str" }, { - "name": "session_entity_type", - "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + "name": "playbook_version", + "type": "google.cloud.dialogflowcx_v3.types.PlaybookVersion" }, { "name": "retry", @@ -11418,22 +11418,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "create_session_entity_type" + "resultType": "google.cloud.dialogflowcx_v3.types.PlaybookVersion", + "shortName": "create_playbook_version" }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_sync.py", + "description": "Sample for CreatePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_create_playbook_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_CreateSessionEntityType_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_CreatePlaybookVersion_sync", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11443,49 +11443,53 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_sync.py" + "title": "dialogflow_v3_generated_playbooks_create_playbook_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.delete_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.create_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "DeleteSessionEntityType" + "shortName": "CreatePlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePlaybookRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "playbook", + "type": "google.cloud.dialogflowcx_v3.types.Playbook" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11499,21 +11503,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_session_entity_type" + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "create_playbook" }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_async.py", + "description": "Sample for CreatePlaybook", + "file": "dialogflow_v3_generated_playbooks_create_playbook_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_DeleteSessionEntityType_async", + "regionTag": "dialogflow_v3_generated_Playbooks_CreatePlaybook_async", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11523,46 +11528,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_async.py" + "title": "dialogflow_v3_generated_playbooks_create_playbook_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.delete_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.create_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.CreatePlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "DeleteSessionEntityType" + "shortName": "CreatePlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreatePlaybookRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "playbook", + "type": "google.cloud.dialogflowcx_v3.types.Playbook" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11576,21 +11587,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_session_entity_type" + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "create_playbook" }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_sync.py", + "description": "Sample for CreatePlaybook", + "file": "dialogflow_v3_generated_playbooks_create_playbook_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_DeleteSessionEntityType_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_CreatePlaybook_sync", "segments": [ { - "end": 49, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11600,42 +11612,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_sync.py" + "title": "dialogflow_v3_generated_playbooks_create_playbook_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.get_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.delete_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "GetSessionEntityType" + "shortName": "DeletePlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePlaybookVersionRequest" }, { "name": "name", @@ -11654,22 +11668,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "get_session_entity_type" + "shortName": "delete_playbook_version" }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_async.py", + "description": "Sample for DeletePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_delete_playbook_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_async", + "regionTag": "dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -11684,38 +11697,36 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_async.py" + "title": "dialogflow_v3_generated_playbooks_delete_playbook_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.get_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.delete_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "GetSessionEntityType" + "shortName": "DeletePlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePlaybookVersionRequest" }, { "name": "name", @@ -11734,22 +11745,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "get_session_entity_type" + "shortName": "delete_playbook_version" }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_sync.py", + "description": "Sample for DeletePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_DeletePlaybookVersion_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -11764,42 +11774,40 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_sync.py" + "title": "dialogflow_v3_generated_playbooks_delete_playbook_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.list_session_entity_types", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.delete_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "ListSessionEntityTypes" + "shortName": "DeletePlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePlaybookRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11815,22 +11823,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", - "shortName": "list_session_entity_types" + "shortName": "delete_playbook" }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_async.py", + "description": "Sample for DeletePlaybook", + "file": "dialogflow_v3_generated_playbooks_delete_playbook_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_ListSessionEntityTypes_async", + "regionTag": "dialogflow_v3_generated_Playbooks_DeletePlaybook_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -11845,41 +11852,39 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_async.py" + "title": "dialogflow_v3_generated_playbooks_delete_playbook_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.list_session_entity_types", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.delete_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.DeletePlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "ListSessionEntityTypes" + "shortName": "DeletePlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeletePlaybookRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11895,22 +11900,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesPager", - "shortName": "list_session_entity_types" + "shortName": "delete_playbook" }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_sync.py", + "description": "Sample for DeletePlaybook", + "file": "dialogflow_v3_generated_playbooks_delete_playbook_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_ListSessionEntityTypes_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_DeletePlaybook_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -11925,47 +11929,37 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_sync.py" + "title": "dialogflow_v3_generated_playbooks_delete_playbook_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.update_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.export_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "UpdateSessionEntityType" + "shortName": "ExportPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.dialogflowcx_v3.types.ExportPlaybookRequest" }, { "name": "retry", @@ -11980,22 +11974,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "update_session_entity_type" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_playbook" }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_async.py", + "description": "Sample for ExportPlaybook", + "file": "dialogflow_v3_generated_playbooks_export_playbook_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_UpdateSessionEntityType_async", + "regionTag": "dialogflow_v3_generated_Playbooks_ExportPlaybook_async", "segments": [ { - "end": 57, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12005,51 +11999,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_async.py" + "title": "dialogflow_v3_generated_playbooks_export_playbook_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.update_session_entity_type", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.export_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ExportPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "UpdateSessionEntityType" + "shortName": "ExportPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.dialogflowcx_v3.types.ExportPlaybookRequest" }, { "name": "retry", @@ -12064,22 +12050,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", - "shortName": "update_session_entity_type" + "resultType": "google.api_core.operation.Operation", + "shortName": "export_playbook" }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_sync.py", + "description": "Sample for ExportPlaybook", + "file": "dialogflow_v3_generated_playbooks_export_playbook_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_SessionEntityTypes_UpdateSessionEntityType_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_ExportPlaybook_sync", "segments": [ { - "end": 57, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12089,44 +12075,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_sync.py" + "title": "dialogflow_v3_generated_playbooks_export_playbook_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.get_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.DetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "DetectIntent" + "shortName": "GetPlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPlaybookVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -12141,22 +12131,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.DetectIntentResponse", - "shortName": "detect_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.PlaybookVersion", + "shortName": "get_playbook_version" }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v3_generated_sessions_detect_intent_async.py", + "description": "Sample for GetPlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_get_playbook_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_DetectIntent_async", + "regionTag": "dialogflow_v3_generated_Playbooks_GetPlaybookVersion_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12166,43 +12156,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_detect_intent_async.py" + "title": "dialogflow_v3_generated_playbooks_get_playbook_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.get_playbook_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.DetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybookVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "DetectIntent" + "shortName": "GetPlaybookVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPlaybookVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -12217,22 +12211,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.DetectIntentResponse", - "shortName": "detect_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.PlaybookVersion", + "shortName": "get_playbook_version" }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v3_generated_sessions_detect_intent_sync.py", + "description": "Sample for GetPlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_get_playbook_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_DetectIntent_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_GetPlaybookVersion_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12242,44 +12236,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_detect_intent_sync.py" + "title": "dialogflow_v3_generated_playbooks_get_playbook_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.fulfill_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.get_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.FulfillIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "FulfillIntent" + "shortName": "GetPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.FulfillIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPlaybookRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -12294,22 +12292,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FulfillIntentResponse", - "shortName": "fulfill_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "get_playbook" }, - "description": "Sample for FulfillIntent", - "file": "dialogflow_v3_generated_sessions_fulfill_intent_async.py", + "description": "Sample for GetPlaybook", + "file": "dialogflow_v3_generated_playbooks_get_playbook_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_FulfillIntent_async", + "regionTag": "dialogflow_v3_generated_Playbooks_GetPlaybook_async", "segments": [ { - "end": 50, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12319,43 +12317,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_fulfill_intent_async.py" + "title": "dialogflow_v3_generated_playbooks_get_playbook_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.fulfill_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.get_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.FulfillIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.GetPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "FulfillIntent" + "shortName": "GetPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.FulfillIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetPlaybookRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -12370,22 +12372,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.FulfillIntentResponse", - "shortName": "fulfill_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "get_playbook" }, - "description": "Sample for FulfillIntent", - "file": "dialogflow_v3_generated_sessions_fulfill_intent_sync.py", + "description": "Sample for GetPlaybook", + "file": "dialogflow_v3_generated_playbooks_get_playbook_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_FulfillIntent_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_GetPlaybook_sync", "segments": [ { - "end": 50, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12395,44 +12397,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_fulfill_intent_sync.py" + "title": "dialogflow_v3_generated_playbooks_get_playbook_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.match_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.import_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.MatchIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "MatchIntent" + "shortName": "ImportPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.MatchIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ImportPlaybookRequest" }, { "name": "retry", @@ -12447,14 +12449,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.MatchIntentResponse", - "shortName": "match_intent" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_playbook" }, - "description": "Sample for MatchIntent", - "file": "dialogflow_v3_generated_sessions_match_intent_async.py", + "description": "Sample for ImportPlaybook", + "file": "dialogflow_v3_generated_playbooks_import_playbook_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_MatchIntent_async", + "regionTag": "dialogflow_v3_generated_Playbooks_ImportPlaybook_async", "segments": [ { "end": 56, @@ -12472,13 +12474,13 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { @@ -12487,28 +12489,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_match_intent_async.py" + "title": "dialogflow_v3_generated_playbooks_import_playbook_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.match_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.import_playbook", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.MatchIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ImportPlaybook", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "MatchIntent" + "shortName": "ImportPlaybook" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.MatchIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ImportPlaybookRequest" }, { "name": "retry", @@ -12523,14 +12525,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.MatchIntentResponse", - "shortName": "match_intent" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_playbook" }, - "description": "Sample for MatchIntent", - "file": "dialogflow_v3_generated_sessions_match_intent_sync.py", + "description": "Sample for ImportPlaybook", + "file": "dialogflow_v3_generated_playbooks_import_playbook_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_MatchIntent_sync", + "regionTag": "dialogflow_v3_generated_Playbooks_ImportPlaybook_sync", "segments": [ { "end": 56, @@ -12548,13 +12550,13 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { @@ -12563,29 +12565,4257 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_match_intent_sync.py" + "title": "dialogflow_v3_generated_playbooks_import_playbook_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.server_streaming_detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.list_playbook_versions", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.ServerStreamingDetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" }, - "shortName": "ServerStreamingDetectIntent" + "shortName": "ListPlaybookVersions" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybookVersionsAsyncPager", + "shortName": "list_playbook_versions" + }, + "description": "Sample for ListPlaybookVersions", + "file": "dialogflow_v3_generated_playbooks_list_playbook_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_ListPlaybookVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_list_playbook_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.list_playbook_versions", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybookVersions", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "ListPlaybookVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListPlaybookVersionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybookVersionsPager", + "shortName": "list_playbook_versions" + }, + "description": "Sample for ListPlaybookVersions", + "file": "dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_ListPlaybookVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_list_playbook_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.list_playbooks", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "ListPlaybooks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybooksAsyncPager", + "shortName": "list_playbooks" + }, + "description": "Sample for ListPlaybooks", + "file": "dialogflow_v3_generated_playbooks_list_playbooks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_ListPlaybooks_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_list_playbooks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.list_playbooks", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.ListPlaybooks", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "ListPlaybooks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListPlaybooksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.playbooks.pagers.ListPlaybooksPager", + "shortName": "list_playbooks" + }, + "description": "Sample for ListPlaybooks", + "file": "dialogflow_v3_generated_playbooks_list_playbooks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_ListPlaybooks_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_list_playbooks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.restore_playbook_version", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "RestorePlaybookVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionResponse", + "shortName": "restore_playbook_version" + }, + "description": "Sample for RestorePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_restore_playbook_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_restore_playbook_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.restore_playbook_version", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.RestorePlaybookVersion", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "RestorePlaybookVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.RestorePlaybookVersionResponse", + "shortName": "restore_playbook_version" + }, + "description": "Sample for RestorePlaybookVersion", + "file": "dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_RestorePlaybookVersion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_restore_playbook_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient", + "shortName": "PlaybooksAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksAsyncClient.update_playbook", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "UpdatePlaybook" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdatePlaybookRequest" + }, + { + "name": "playbook", + "type": "google.cloud.dialogflowcx_v3.types.Playbook" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "update_playbook" + }, + "description": "Sample for UpdatePlaybook", + "file": "dialogflow_v3_generated_playbooks_update_playbook_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_UpdatePlaybook_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_update_playbook_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient", + "shortName": "PlaybooksClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.PlaybooksClient.update_playbook", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks.UpdatePlaybook", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Playbooks", + "shortName": "Playbooks" + }, + "shortName": "UpdatePlaybook" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdatePlaybookRequest" + }, + { + "name": "playbook", + "type": "google.cloud.dialogflowcx_v3.types.Playbook" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.Playbook", + "shortName": "update_playbook" + }, + "description": "Sample for UpdatePlaybook", + "file": "dialogflow_v3_generated_playbooks_update_playbook_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Playbooks_UpdatePlaybook_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_playbooks_update_playbook_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", + "shortName": "SecuritySettingsServiceAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.create_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.CreateSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "CreateSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_settings", + "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "create_security_settings" + }, + "description": "Sample for CreateSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_create_security_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_CreateSecuritySettings_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_create_security_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", + "shortName": "SecuritySettingsServiceClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.create_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.CreateSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "CreateSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_settings", + "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "create_security_settings" + }, + "description": "Sample for CreateSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_create_security_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_CreateSecuritySettings_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_create_security_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", + "shortName": "SecuritySettingsServiceAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.delete_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.DeleteSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "DeleteSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_security_settings" + }, + "description": "Sample for DeleteSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_delete_security_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_DeleteSecuritySettings_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_delete_security_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", + "shortName": "SecuritySettingsServiceClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.delete_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.DeleteSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "DeleteSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_security_settings" + }, + "description": "Sample for DeleteSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_delete_security_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_DeleteSecuritySettings_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_delete_security_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", + "shortName": "SecuritySettingsServiceAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.get_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "GetSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "get_security_settings" + }, + "description": "Sample for GetSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_get_security_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_GetSecuritySettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_get_security_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", + "shortName": "SecuritySettingsServiceClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.get_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "GetSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "get_security_settings" + }, + "description": "Sample for GetSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_get_security_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_GetSecuritySettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_get_security_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", + "shortName": "SecuritySettingsServiceAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.list_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.ListSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "ListSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager", + "shortName": "list_security_settings" + }, + "description": "Sample for ListSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_list_security_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_ListSecuritySettings_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_list_security_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", + "shortName": "SecuritySettingsServiceClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.list_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.ListSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "ListSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsPager", + "shortName": "list_security_settings" + }, + "description": "Sample for ListSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_list_security_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_ListSecuritySettings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_list_security_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient", + "shortName": "SecuritySettingsServiceAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceAsyncClient.update_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "UpdateSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest" + }, + { + "name": "security_settings", + "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "update_security_settings" + }, + "description": "Sample for UpdateSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_update_security_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_UpdateSecuritySettings_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_update_security_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient", + "shortName": "SecuritySettingsServiceClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SecuritySettingsServiceClient.update_security_settings", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SecuritySettingsService", + "shortName": "SecuritySettingsService" + }, + "shortName": "UpdateSecuritySettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest" + }, + { + "name": "security_settings", + "type": "google.cloud.dialogflowcx_v3.types.SecuritySettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SecuritySettings", + "shortName": "update_security_settings" + }, + "description": "Sample for UpdateSecuritySettings", + "file": "dialogflow_v3_generated_security_settings_service_update_security_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SecuritySettingsService_UpdateSecuritySettings_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_security_settings_service_update_security_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.create_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "CreateSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "create_session_entity_type" + }, + "description": "Sample for CreateSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_CreateSessionEntityType_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.create_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "CreateSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "create_session_entity_type" + }, + "description": "Sample for CreateSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_CreateSessionEntityType_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_create_session_entity_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.delete_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "DeleteSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_session_entity_type" + }, + "description": "Sample for DeleteSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_DeleteSessionEntityType_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.delete_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "DeleteSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_session_entity_type" + }, + "description": "Sample for DeleteSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_DeleteSessionEntityType_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_delete_session_entity_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.get_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "GetSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "get_session_entity_type" + }, + "description": "Sample for GetSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.get_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "GetSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "get_session_entity_type" + }, + "description": "Sample for GetSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_GetSessionEntityType_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_get_session_entity_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.list_session_entity_types", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "ListSessionEntityTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", + "shortName": "list_session_entity_types" + }, + "description": "Sample for ListSessionEntityTypes", + "file": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_ListSessionEntityTypes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.list_session_entity_types", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "ListSessionEntityTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesPager", + "shortName": "list_session_entity_types" + }, + "description": "Sample for ListSessionEntityTypes", + "file": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_ListSessionEntityTypes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_list_session_entity_types_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesAsyncClient.update_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "UpdateSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "update_session_entity_type" + }, + "description": "Sample for UpdateSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_UpdateSessionEntityType_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionEntityTypesClient.update_session_entity_type", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.SessionEntityTypes", + "shortName": "SessionEntityTypes" + }, + "shortName": "UpdateSessionEntityType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflowcx_v3.types.SessionEntityType" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.SessionEntityType", + "shortName": "update_session_entity_type" + }, + "description": "Sample for UpdateSessionEntityType", + "file": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_SessionEntityTypes_UpdateSessionEntityType_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_session_entity_types_update_session_entity_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.DetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "DetectIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.DetectIntentResponse", + "shortName": "detect_intent" + }, + "description": "Sample for DetectIntent", + "file": "dialogflow_v3_generated_sessions_detect_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_DetectIntent_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_detect_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.DetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "DetectIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.DetectIntentResponse", + "shortName": "detect_intent" + }, + "description": "Sample for DetectIntent", + "file": "dialogflow_v3_generated_sessions_detect_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_DetectIntent_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_detect_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.fulfill_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.FulfillIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "FulfillIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.FulfillIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.FulfillIntentResponse", + "shortName": "fulfill_intent" + }, + "description": "Sample for FulfillIntent", + "file": "dialogflow_v3_generated_sessions_fulfill_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_FulfillIntent_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_fulfill_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.fulfill_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.FulfillIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "FulfillIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.FulfillIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.FulfillIntentResponse", + "shortName": "fulfill_intent" + }, + "description": "Sample for FulfillIntent", + "file": "dialogflow_v3_generated_sessions_fulfill_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_FulfillIntent_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_fulfill_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.match_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.MatchIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "MatchIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.MatchIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.MatchIntentResponse", + "shortName": "match_intent" + }, + "description": "Sample for MatchIntent", + "file": "dialogflow_v3_generated_sessions_match_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_MatchIntent_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_match_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.match_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.MatchIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "MatchIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.MatchIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.MatchIntentResponse", + "shortName": "match_intent" + }, + "description": "Sample for MatchIntent", + "file": "dialogflow_v3_generated_sessions_match_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_MatchIntent_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_match_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.server_streaming_detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.ServerStreamingDetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "ServerStreamingDetectIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.DetectIntentResponse]", + "shortName": "server_streaming_detect_intent" + }, + "description": "Sample for ServerStreamingDetectIntent", + "file": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_ServerStreamingDetectIntent_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.server_streaming_detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.ServerStreamingDetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "ServerStreamingDetectIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.DetectIntentResponse]", + "shortName": "server_streaming_detect_intent" + }, + "description": "Sample for ServerStreamingDetectIntent", + "file": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_ServerStreamingDetectIntent_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.streaming_detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "StreamingDetectIntent" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]", + "shortName": "streaming_detect_intent" + }, + "description": "Sample for StreamingDetectIntent", + "file": "dialogflow_v3_generated_sessions_streaming_detect_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_StreamingDetectIntent_async", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 59, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 60, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_streaming_detect_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.streaming_detect_intent", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "StreamingDetectIntent" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]", + "shortName": "streaming_detect_intent" + }, + "description": "Sample for StreamingDetectIntent", + "file": "dialogflow_v3_generated_sessions_streaming_detect_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_StreamingDetectIntent_sync", + "segments": [ + { + "end": 66, + "start": 27, + "type": "FULL" + }, + { + "end": 66, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 59, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 62, + "start": 60, + "type": "REQUEST_EXECUTION" + }, + { + "end": 67, + "start": 63, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_streaming_detect_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.submit_answer_feedback", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.SubmitAnswerFeedback", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "SubmitAnswerFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.SubmitAnswerFeedbackRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.AnswerFeedback", + "shortName": "submit_answer_feedback" + }, + "description": "Sample for SubmitAnswerFeedback", + "file": "dialogflow_v3_generated_sessions_submit_answer_feedback_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_SubmitAnswerFeedback_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_submit_answer_feedback_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", + "shortName": "SessionsClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.submit_answer_feedback", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions.SubmitAnswerFeedback", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.Sessions", + "shortName": "Sessions" + }, + "shortName": "SubmitAnswerFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.SubmitAnswerFeedbackRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.AnswerFeedback", + "shortName": "submit_answer_feedback" + }, + "description": "Sample for SubmitAnswerFeedback", + "file": "dialogflow_v3_generated_sessions_submit_answer_feedback_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_Sessions_SubmitAnswerFeedback_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_sessions_submit_answer_feedback_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.batch_delete_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "BatchDeleteTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "batch_delete_test_cases" + }, + "description": "Sample for BatchDeleteTestCases", + "file": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_BatchDeleteTestCases_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.batch_delete_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "BatchDeleteTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "batch_delete_test_cases" + }, + "description": "Sample for BatchDeleteTestCases", + "file": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_BatchDeleteTestCases_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.batch_run_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "BatchRunTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_run_test_cases" + }, + "description": "Sample for BatchRunTestCases", + "file": "dialogflow_v3_generated_test_cases_batch_run_test_cases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_BatchRunTestCases_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_batch_run_test_cases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.batch_run_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "BatchRunTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_run_test_cases" + }, + "description": "Sample for BatchRunTestCases", + "file": "dialogflow_v3_generated_test_cases_batch_run_test_cases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_BatchRunTestCases_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_batch_run_test_cases_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.calculate_coverage", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "CalculateCoverage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse", + "shortName": "calculate_coverage" + }, + "description": "Sample for CalculateCoverage", + "file": "dialogflow_v3_generated_test_cases_calculate_coverage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_CalculateCoverage_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_calculate_coverage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.calculate_coverage", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "CalculateCoverage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse", + "shortName": "calculate_coverage" + }, + "description": "Sample for CalculateCoverage", + "file": "dialogflow_v3_generated_test_cases_calculate_coverage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_CalculateCoverage_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_calculate_coverage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.create_test_case", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "CreateTestCase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_case", + "type": "google.cloud.dialogflowcx_v3.types.TestCase" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "create_test_case" + }, + "description": "Sample for CreateTestCase", + "file": "dialogflow_v3_generated_test_cases_create_test_case_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_CreateTestCase_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_create_test_case_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.create_test_case", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "CreateTestCase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "test_case", + "type": "google.cloud.dialogflowcx_v3.types.TestCase" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "create_test_case" + }, + "description": "Sample for CreateTestCase", + "file": "dialogflow_v3_generated_test_cases_create_test_case_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_CreateTestCase_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_create_test_case_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.export_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "ExportTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_test_cases" + }, + "description": "Sample for ExportTestCases", + "file": "dialogflow_v3_generated_test_cases_export_test_cases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_ExportTestCases_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_export_test_cases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.export_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "ExportTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_test_cases" + }, + "description": "Sample for ExportTestCases", + "file": "dialogflow_v3_generated_test_cases_export_test_cases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_ExportTestCases_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_export_test_cases_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.get_test_case_result", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "GetTestCaseResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.TestCaseResult", + "shortName": "get_test_case_result" + }, + "description": "Sample for GetTestCaseResult", + "file": "dialogflow_v3_generated_test_cases_get_test_case_result_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_GetTestCaseResult_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_get_test_case_result_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.get_test_case_result", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "GetTestCaseResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.TestCaseResult", + "shortName": "get_test_case_result" + }, + "description": "Sample for GetTestCaseResult", + "file": "dialogflow_v3_generated_test_cases_get_test_case_result_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_GetTestCaseResult_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_get_test_case_result_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.get_test_case", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCase", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "GetTestCase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "get_test_case" + }, + "description": "Sample for GetTestCase", + "file": "dialogflow_v3_generated_test_cases_get_test_case_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_GetTestCase_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_get_test_case_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.get_test_case", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCase", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "GetTestCase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -12600,22 +16830,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.DetectIntentResponse]", - "shortName": "server_streaming_detect_intent" + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "get_test_case" }, - "description": "Sample for ServerStreamingDetectIntent", - "file": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_async.py", + "description": "Sample for GetTestCase", + "file": "dialogflow_v3_generated_test_cases_get_test_case_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_ServerStreamingDetectIntent_async", + "regionTag": "dialogflow_v3_generated_TestCases_GetTestCase_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12625,43 +16855,120 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dialogflow_v3_generated_test_cases_get_test_case_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" + }, + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.import_test_cases", + "method": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases", + "service": { + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" + }, + "shortName": "ImportTestCases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_test_cases" + }, + "description": "Sample for ImportTestCases", + "file": "dialogflow_v3_generated_test_cases_import_test_cases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v3_generated_TestCases_ImportTestCases_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 58, + "end": 57, "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_async.py" + "title": "dialogflow_v3_generated_test_cases_import_test_cases_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.server_streaming_detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.import_test_cases", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.ServerStreamingDetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" }, - "shortName": "ServerStreamingDetectIntent" + "shortName": "ImportTestCases" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.DetectIntentRequest" + "type": "google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest" }, { "name": "retry", @@ -12676,22 +16983,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.DetectIntentResponse]", - "shortName": "server_streaming_detect_intent" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_test_cases" }, - "description": "Sample for ServerStreamingDetectIntent", - "file": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_sync.py", + "description": "Sample for ImportTestCases", + "file": "dialogflow_v3_generated_test_cases_import_test_cases_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_ServerStreamingDetectIntent_sync", + "regionTag": "dialogflow_v3_generated_TestCases_ImportTestCases_sync", "segments": [ { - "end": 57, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 56, "start": 27, "type": "SHORT" }, @@ -12701,44 +17008,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { "end": 53, - "start": 51, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 58, + "end": 57, "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_server_streaming_detect_intent_sync.py" + "title": "dialogflow_v3_generated_test_cases_import_test_cases_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.streaming_detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.list_test_case_results", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" }, - "shortName": "StreamingDetectIntent" + "shortName": "ListTestCaseResults" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest]" + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -12753,22 +17064,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" + "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsAsyncPager", + "shortName": "list_test_case_results" }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v3_generated_sessions_streaming_detect_intent_async.py", + "description": "Sample for ListTestCaseResults", + "file": "dialogflow_v3_generated_test_cases_list_test_case_results_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_StreamingDetectIntent_async", + "regionTag": "dialogflow_v3_generated_TestCases_ListTestCaseResults_async", "segments": [ { - "end": 66, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 66, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12778,43 +17089,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 59, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 62, - "start": 60, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 67, - "start": 63, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_streaming_detect_intent_async.py" + "title": "dialogflow_v3_generated_test_cases_list_test_case_results_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.streaming_detect_intent", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.list_test_case_results", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" }, - "shortName": "StreamingDetectIntent" + "shortName": "ListTestCaseResults" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest]" + "name": "request", + "type": "google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -12829,22 +17144,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" + "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsPager", + "shortName": "list_test_case_results" }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v3_generated_sessions_streaming_detect_intent_sync.py", + "description": "Sample for ListTestCaseResults", + "file": "dialogflow_v3_generated_test_cases_list_test_case_results_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_StreamingDetectIntent_sync", + "regionTag": "dialogflow_v3_generated_TestCases_ListTestCaseResults_sync", "segments": [ { - "end": 66, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 66, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12854,44 +17169,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 59, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 62, - "start": 60, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 67, - "start": 63, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_streaming_detect_intent_sync.py" + "title": "dialogflow_v3_generated_test_cases_list_test_case_results_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", + "shortName": "TestCasesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsAsyncClient.submit_answer_feedback", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.list_test_cases", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.SubmitAnswerFeedback", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCases", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" }, - "shortName": "SubmitAnswerFeedback" + "shortName": "ListTestCases" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.SubmitAnswerFeedbackRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListTestCasesRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -12906,14 +17225,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.AnswerFeedback", - "shortName": "submit_answer_feedback" + "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesAsyncPager", + "shortName": "list_test_cases" }, - "description": "Sample for SubmitAnswerFeedback", - "file": "dialogflow_v3_generated_sessions_submit_answer_feedback_async.py", + "description": "Sample for ListTestCases", + "file": "dialogflow_v3_generated_test_cases_list_test_cases_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_SubmitAnswerFeedback_async", + "regionTag": "dialogflow_v3_generated_TestCases_ListTestCases_async", "segments": [ { "end": 52, @@ -12931,43 +17250,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_submit_answer_feedback_async.py" + "title": "dialogflow_v3_generated_test_cases_list_test_cases_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", + "shortName": "TestCasesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.SessionsClient.submit_answer_feedback", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.list_test_cases", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions.SubmitAnswerFeedback", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCases", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.cx.v3.TestCases", + "shortName": "TestCases" }, - "shortName": "SubmitAnswerFeedback" + "shortName": "ListTestCases" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.SubmitAnswerFeedbackRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListTestCasesRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -12982,14 +17305,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.AnswerFeedback", - "shortName": "submit_answer_feedback" + "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesPager", + "shortName": "list_test_cases" }, - "description": "Sample for SubmitAnswerFeedback", - "file": "dialogflow_v3_generated_sessions_submit_answer_feedback_sync.py", + "description": "Sample for ListTestCases", + "file": "dialogflow_v3_generated_test_cases_list_test_cases_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_Sessions_SubmitAnswerFeedback_sync", + "regionTag": "dialogflow_v3_generated_TestCases_ListTestCases_sync", "segments": [ { "end": 52, @@ -13007,22 +17330,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_sessions_submit_answer_feedback_sync.py" + "title": "dialogflow_v3_generated_test_cases_list_test_cases_sync.py" }, { "canonical": true, @@ -13032,23 +17355,19 @@ "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", "shortName": "TestCasesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.batch_delete_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.run_test_case", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.RunTestCase", "service": { "fullName": "google.cloud.dialogflow.cx.v3.TestCases", "shortName": "TestCases" }, - "shortName": "BatchDeleteTestCases" + "shortName": "RunTestCase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.RunTestCaseRequest" }, { "name": "retry", @@ -13063,21 +17382,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "batch_delete_test_cases" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_test_case" }, - "description": "Sample for BatchDeleteTestCases", - "file": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_async.py", + "description": "Sample for RunTestCase", + "file": "dialogflow_v3_generated_test_cases_run_test_case_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_BatchDeleteTestCases_async", + "regionTag": "dialogflow_v3_generated_TestCases_RunTestCase_async", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -13087,20 +17407,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_async.py" + "title": "dialogflow_v3_generated_test_cases_run_test_case_async.py" }, { "canonical": true, @@ -13109,23 +17431,19 @@ "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", "shortName": "TestCasesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.batch_delete_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.run_test_case", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.RunTestCase", "service": { "fullName": "google.cloud.dialogflow.cx.v3.TestCases", "shortName": "TestCases" }, - "shortName": "BatchDeleteTestCases" + "shortName": "RunTestCase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.dialogflowcx_v3.types.RunTestCaseRequest" }, { "name": "retry", @@ -13140,21 +17458,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "batch_delete_test_cases" + "resultType": "google.api_core.operation.Operation", + "shortName": "run_test_case" }, - "description": "Sample for BatchDeleteTestCases", - "file": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_sync.py", + "description": "Sample for RunTestCase", + "file": "dialogflow_v3_generated_test_cases_run_test_case_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_BatchDeleteTestCases_sync", + "regionTag": "dialogflow_v3_generated_TestCases_RunTestCase_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -13164,20 +17483,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_batch_delete_test_cases_sync.py" + "title": "dialogflow_v3_generated_test_cases_run_test_case_sync.py" }, { "canonical": true, @@ -13187,19 +17508,27 @@ "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", "shortName": "TestCasesAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.batch_run_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.update_test_case", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase", "service": { "fullName": "google.cloud.dialogflow.cx.v3.TestCases", "shortName": "TestCases" }, - "shortName": "BatchRunTestCases" + "shortName": "UpdateTestCase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest" + }, + { + "name": "test_case", + "type": "google.cloud.dialogflowcx_v3.types.TestCase" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13214,22 +17543,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_run_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "update_test_case" }, - "description": "Sample for BatchRunTestCases", - "file": "dialogflow_v3_generated_test_cases_batch_run_test_cases_async.py", + "description": "Sample for UpdateTestCase", + "file": "dialogflow_v3_generated_test_cases_update_test_case_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_BatchRunTestCases_async", + "regionTag": "dialogflow_v3_generated_TestCases_UpdateTestCase_async", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -13239,22 +17568,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_batch_run_test_cases_async.py" + "title": "dialogflow_v3_generated_test_cases_update_test_case_async.py" }, { "canonical": true, @@ -13263,19 +17592,27 @@ "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", "shortName": "TestCasesClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.batch_run_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.update_test_case", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase", "service": { "fullName": "google.cloud.dialogflow.cx.v3.TestCases", "shortName": "TestCases" }, - "shortName": "BatchRunTestCases" + "shortName": "UpdateTestCase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest" + }, + { + "name": "test_case", + "type": "google.cloud.dialogflowcx_v3.types.TestCase" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13290,22 +17627,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_run_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", + "shortName": "update_test_case" }, - "description": "Sample for BatchRunTestCases", - "file": "dialogflow_v3_generated_test_cases_batch_run_test_cases_sync.py", + "description": "Sample for UpdateTestCase", + "file": "dialogflow_v3_generated_test_cases_update_test_case_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_BatchRunTestCases_sync", + "regionTag": "dialogflow_v3_generated_TestCases_UpdateTestCase_sync", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -13315,44 +17652,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_batch_run_test_cases_sync.py" + "title": "dialogflow_v3_generated_test_cases_update_test_case_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.calculate_coverage", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.create_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "CalculateCoverage" + "shortName": "CreateToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateToolVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tool_version", + "type": "google.cloud.dialogflowcx_v3.types.ToolVersion" }, { "name": "retry", @@ -13367,22 +17712,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse", - "shortName": "calculate_coverage" + "resultType": "google.cloud.dialogflowcx_v3.types.ToolVersion", + "shortName": "create_tool_version" }, - "description": "Sample for CalculateCoverage", - "file": "dialogflow_v3_generated_test_cases_calculate_coverage_async.py", + "description": "Sample for CreateToolVersion", + "file": "dialogflow_v3_generated_tools_create_tool_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_CalculateCoverage_async", + "regionTag": "dialogflow_v3_generated_Tools_CreateToolVersion_async", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -13392,43 +17737,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_calculate_coverage_async.py" + "title": "dialogflow_v3_generated_tools_create_tool_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.calculate_coverage", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.create_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.CreateToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "CalculateCoverage" + "shortName": "CreateToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateToolVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tool_version", + "type": "google.cloud.dialogflowcx_v3.types.ToolVersion" }, { "name": "retry", @@ -13443,22 +17796,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse", - "shortName": "calculate_coverage" + "resultType": "google.cloud.dialogflowcx_v3.types.ToolVersion", + "shortName": "create_tool_version" }, - "description": "Sample for CalculateCoverage", - "file": "dialogflow_v3_generated_test_cases_calculate_coverage_sync.py", + "description": "Sample for CreateToolVersion", + "file": "dialogflow_v3_generated_tools_create_tool_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_CalculateCoverage_sync", + "regionTag": "dialogflow_v3_generated_Tools_CreateToolVersion_sync", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -13468,52 +17821,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_calculate_coverage_sync.py" + "title": "dialogflow_v3_generated_tools_create_tool_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.create_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.create_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.CreateTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "CreateTestCase" + "shortName": "CreateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateToolRequest" }, { "name": "parent", "type": "str" }, { - "name": "test_case", - "type": "google.cloud.dialogflowcx_v3.types.TestCase" + "name": "tool", + "type": "google.cloud.dialogflowcx_v3.types.Tool" }, { "name": "retry", @@ -13528,22 +17881,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "create_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "create_tool" }, - "description": "Sample for CreateTestCase", - "file": "dialogflow_v3_generated_test_cases_create_test_case_async.py", + "description": "Sample for CreateTool", + "file": "dialogflow_v3_generated_tools_create_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_CreateTestCase_async", + "regionTag": "dialogflow_v3_generated_Tools_CreateTool_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -13553,51 +17906,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_create_test_case_async.py" + "title": "dialogflow_v3_generated_tools_create_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.create_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.create_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.CreateTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "CreateTestCase" + "shortName": "CreateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.CreateToolRequest" }, { "name": "parent", "type": "str" }, { - "name": "test_case", - "type": "google.cloud.dialogflowcx_v3.types.TestCase" + "name": "tool", + "type": "google.cloud.dialogflowcx_v3.types.Tool" }, { "name": "retry", @@ -13612,22 +17965,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "create_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "create_tool" }, - "description": "Sample for CreateTestCase", - "file": "dialogflow_v3_generated_test_cases_create_test_case_sync.py", + "description": "Sample for CreateTool", + "file": "dialogflow_v3_generated_tools_create_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_CreateTestCase_sync", + "regionTag": "dialogflow_v3_generated_Tools_CreateTool_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -13637,44 +17990,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_create_test_case_sync.py" + "title": "dialogflow_v3_generated_tools_create_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.export_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.delete_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ExportTestCases" + "shortName": "DeleteToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteToolVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -13689,22 +18046,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_test_cases" + "shortName": "delete_tool_version" }, - "description": "Sample for ExportTestCases", - "file": "dialogflow_v3_generated_test_cases_export_test_cases_async.py", + "description": "Sample for DeleteToolVersion", + "file": "dialogflow_v3_generated_tools_delete_tool_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ExportTestCases_async", + "regionTag": "dialogflow_v3_generated_Tools_DeleteToolVersion_async", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -13714,43 +18070,45 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_export_test_cases_async.py" + "title": "dialogflow_v3_generated_tools_delete_tool_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.export_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.delete_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.DeleteToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ExportTestCases" + "shortName": "DeleteToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteToolVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -13765,22 +18123,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_test_cases" + "shortName": "delete_tool_version" }, - "description": "Sample for ExportTestCases", - "file": "dialogflow_v3_generated_test_cases_export_test_cases_sync.py", + "description": "Sample for DeleteToolVersion", + "file": "dialogflow_v3_generated_tools_delete_tool_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ExportTestCases_sync", + "regionTag": "dialogflow_v3_generated_Tools_DeleteToolVersion_sync", "segments": [ { - "end": 56, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 49, "start": 27, "type": "SHORT" }, @@ -13790,44 +18147,42 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_export_test_cases_sync.py" + "title": "dialogflow_v3_generated_tools_delete_tool_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.get_test_case_result", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.delete_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.DeleteTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "GetTestCaseResult" + "shortName": "DeleteTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteToolRequest" }, { "name": "name", @@ -13846,22 +18201,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCaseResult", - "shortName": "get_test_case_result" + "shortName": "delete_tool" }, - "description": "Sample for GetTestCaseResult", - "file": "dialogflow_v3_generated_test_cases_get_test_case_result_async.py", + "description": "Sample for DeleteTool", + "file": "dialogflow_v3_generated_tools_delete_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_GetTestCaseResult_async", + "regionTag": "dialogflow_v3_generated_Tools_DeleteTool_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -13876,38 +18230,36 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_get_test_case_result_async.py" + "title": "dialogflow_v3_generated_tools_delete_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.get_test_case_result", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.delete_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.DeleteTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "GetTestCaseResult" + "shortName": "DeleteTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest" + "type": "google.cloud.dialogflowcx_v3.types.DeleteToolRequest" }, { "name": "name", @@ -13926,22 +18278,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCaseResult", - "shortName": "get_test_case_result" + "shortName": "delete_tool" }, - "description": "Sample for GetTestCaseResult", - "file": "dialogflow_v3_generated_test_cases_get_test_case_result_sync.py", + "description": "Sample for DeleteTool", + "file": "dialogflow_v3_generated_tools_delete_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_GetTestCaseResult_sync", + "regionTag": "dialogflow_v3_generated_Tools_DeleteTool_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -13956,39 +18307,37 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_get_test_case_result_sync.py" + "title": "dialogflow_v3_generated_tools_delete_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.get_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.get_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.GetToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "GetTestCase" + "shortName": "GetToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetToolVersionRequest" }, { "name": "name", @@ -14007,14 +18356,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "get_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.ToolVersion", + "shortName": "get_tool_version" }, - "description": "Sample for GetTestCase", - "file": "dialogflow_v3_generated_test_cases_get_test_case_async.py", + "description": "Sample for GetToolVersion", + "file": "dialogflow_v3_generated_tools_get_tool_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_GetTestCase_async", + "regionTag": "dialogflow_v3_generated_Tools_GetToolVersion_async", "segments": [ { "end": 51, @@ -14047,28 +18396,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_get_test_case_async.py" + "title": "dialogflow_v3_generated_tools_get_tool_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.get_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.get_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.GetTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.GetToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "GetTestCase" + "shortName": "GetToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.GetTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetToolVersionRequest" }, { "name": "name", @@ -14087,14 +18436,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "get_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.ToolVersion", + "shortName": "get_tool_version" }, - "description": "Sample for GetTestCase", - "file": "dialogflow_v3_generated_test_cases_get_test_case_sync.py", + "description": "Sample for GetToolVersion", + "file": "dialogflow_v3_generated_tools_get_tool_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_GetTestCase_sync", + "regionTag": "dialogflow_v3_generated_Tools_GetToolVersion_sync", "segments": [ { "end": 51, @@ -14127,29 +18476,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_get_test_case_sync.py" + "title": "dialogflow_v3_generated_tools_get_tool_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.import_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.get_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.GetTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ImportTestCases" + "shortName": "GetTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetToolRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14164,22 +18517,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "get_tool" }, - "description": "Sample for ImportTestCases", - "file": "dialogflow_v3_generated_test_cases_import_test_cases_async.py", + "description": "Sample for GetTool", + "file": "dialogflow_v3_generated_tools_get_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ImportTestCases_async", + "regionTag": "dialogflow_v3_generated_Tools_GetTool_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14189,43 +18542,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_import_test_cases_async.py" + "title": "dialogflow_v3_generated_tools_get_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.import_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.get_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.GetTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ImportTestCases" + "shortName": "GetTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.GetToolRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14240,22 +18597,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "get_tool" }, - "description": "Sample for ImportTestCases", - "file": "dialogflow_v3_generated_test_cases_import_test_cases_sync.py", + "description": "Sample for GetTool", + "file": "dialogflow_v3_generated_tools_get_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ImportTestCases_sync", + "regionTag": "dialogflow_v3_generated_Tools_GetTool_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14265,44 +18622,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_import_test_cases_sync.py" + "title": "dialogflow_v3_generated_tools_get_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.list_test_case_results", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.list_tool_versions", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.ListToolVersions", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ListTestCaseResults" + "shortName": "ListToolVersions" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest" }, { "name": "parent", @@ -14321,14 +18678,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsAsyncPager", - "shortName": "list_test_case_results" + "resultType": "google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolVersionsAsyncPager", + "shortName": "list_tool_versions" }, - "description": "Sample for ListTestCaseResults", - "file": "dialogflow_v3_generated_test_cases_list_test_case_results_async.py", + "description": "Sample for ListToolVersions", + "file": "dialogflow_v3_generated_tools_list_tool_versions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ListTestCaseResults_async", + "regionTag": "dialogflow_v3_generated_Tools_ListToolVersions_async", "segments": [ { "end": 52, @@ -14361,28 +18718,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_list_test_case_results_async.py" + "title": "dialogflow_v3_generated_tools_list_tool_versions_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.list_test_case_results", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.list_tool_versions", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.ListToolVersions", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ListTestCaseResults" + "shortName": "ListToolVersions" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListToolVersionsRequest" }, { "name": "parent", @@ -14401,14 +18758,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsPager", - "shortName": "list_test_case_results" + "resultType": "google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolVersionsPager", + "shortName": "list_tool_versions" }, - "description": "Sample for ListTestCaseResults", - "file": "dialogflow_v3_generated_test_cases_list_test_case_results_sync.py", + "description": "Sample for ListToolVersions", + "file": "dialogflow_v3_generated_tools_list_tool_versions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ListTestCaseResults_sync", + "regionTag": "dialogflow_v3_generated_Tools_ListToolVersions_sync", "segments": [ { "end": 52, @@ -14441,29 +18798,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_list_test_case_results_sync.py" + "title": "dialogflow_v3_generated_tools_list_tool_versions_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.list_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.list_tools", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.ListTools", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ListTestCases" + "shortName": "ListTools" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListToolsRequest" }, { "name": "parent", @@ -14482,14 +18839,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesAsyncPager", - "shortName": "list_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolsAsyncPager", + "shortName": "list_tools" }, - "description": "Sample for ListTestCases", - "file": "dialogflow_v3_generated_test_cases_list_test_cases_async.py", + "description": "Sample for ListTools", + "file": "dialogflow_v3_generated_tools_list_tools_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ListTestCases_async", + "regionTag": "dialogflow_v3_generated_Tools_ListTools_async", "segments": [ { "end": 52, @@ -14522,28 +18879,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_list_test_cases_async.py" + "title": "dialogflow_v3_generated_tools_list_tools_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.list_test_cases", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.list_tools", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.ListTestCases", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.ListTools", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "ListTestCases" + "shortName": "ListTools" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.ListTestCasesRequest" + "type": "google.cloud.dialogflowcx_v3.types.ListToolsRequest" }, { "name": "parent", @@ -14562,14 +18919,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesPager", - "shortName": "list_test_cases" + "resultType": "google.cloud.dialogflowcx_v3.services.tools.pagers.ListToolsPager", + "shortName": "list_tools" }, - "description": "Sample for ListTestCases", - "file": "dialogflow_v3_generated_test_cases_list_test_cases_sync.py", + "description": "Sample for ListTools", + "file": "dialogflow_v3_generated_tools_list_tools_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_ListTestCases_sync", + "regionTag": "dialogflow_v3_generated_Tools_ListTools_sync", "segments": [ { "end": 52, @@ -14602,29 +18959,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_list_test_cases_sync.py" + "title": "dialogflow_v3_generated_tools_list_tools_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.run_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.restore_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.RunTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "RunTestCase" + "shortName": "RestoreToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.RunTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.RestoreToolVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14639,22 +19000,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "run_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.RestoreToolVersionResponse", + "shortName": "restore_tool_version" }, - "description": "Sample for RunTestCase", - "file": "dialogflow_v3_generated_test_cases_run_test_case_async.py", + "description": "Sample for RestoreToolVersion", + "file": "dialogflow_v3_generated_tools_restore_tool_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_RunTestCase_async", + "regionTag": "dialogflow_v3_generated_Tools_RestoreToolVersion_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14669,38 +19030,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_run_test_case_async.py" + "title": "dialogflow_v3_generated_tools_restore_tool_version_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.run_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.restore_tool_version", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.RunTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.RestoreToolVersion", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "RunTestCase" + "shortName": "RestoreToolVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.RunTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.RestoreToolVersionRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14715,22 +19080,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "run_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.RestoreToolVersionResponse", + "shortName": "restore_tool_version" }, - "description": "Sample for RunTestCase", - "file": "dialogflow_v3_generated_test_cases_run_test_case_sync.py", + "description": "Sample for RestoreToolVersion", + "file": "dialogflow_v3_generated_tools_restore_tool_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_RunTestCase_sync", + "regionTag": "dialogflow_v3_generated_Tools_RestoreToolVersion_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14745,43 +19110,43 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_run_test_case_sync.py" + "title": "dialogflow_v3_generated_tools_restore_tool_version_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient", - "shortName": "TestCasesAsyncClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesAsyncClient.update_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsAsyncClient.update_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.UpdateTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "UpdateTestCase" + "shortName": "UpdateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateToolRequest" }, { - "name": "test_case", - "type": "google.cloud.dialogflowcx_v3.types.TestCase" + "name": "tool", + "type": "google.cloud.dialogflowcx_v3.types.Tool" }, { "name": "update_mask", @@ -14800,22 +19165,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "update_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "update_tool" }, - "description": "Sample for UpdateTestCase", - "file": "dialogflow_v3_generated_test_cases_update_test_case_async.py", + "description": "Sample for UpdateTool", + "file": "dialogflow_v3_generated_tools_update_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_UpdateTestCase_async", + "regionTag": "dialogflow_v3_generated_Tools_UpdateTool_async", "segments": [ { - "end": 54, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 56, "start": 27, "type": "SHORT" }, @@ -14825,47 +19190,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_update_test_case_async.py" + "title": "dialogflow_v3_generated_tools_update_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient", - "shortName": "TestCasesClient" + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflowcx_v3.TestCasesClient.update_test_case", + "fullName": "google.cloud.dialogflowcx_v3.ToolsClient.update_tool", "method": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase", + "fullName": "google.cloud.dialogflow.cx.v3.Tools.UpdateTool", "service": { - "fullName": "google.cloud.dialogflow.cx.v3.TestCases", - "shortName": "TestCases" + "fullName": "google.cloud.dialogflow.cx.v3.Tools", + "shortName": "Tools" }, - "shortName": "UpdateTestCase" + "shortName": "UpdateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest" + "type": "google.cloud.dialogflowcx_v3.types.UpdateToolRequest" }, { - "name": "test_case", - "type": "google.cloud.dialogflowcx_v3.types.TestCase" + "name": "tool", + "type": "google.cloud.dialogflowcx_v3.types.Tool" }, { "name": "update_mask", @@ -14884,22 +19249,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflowcx_v3.types.TestCase", - "shortName": "update_test_case" + "resultType": "google.cloud.dialogflowcx_v3.types.Tool", + "shortName": "update_tool" }, - "description": "Sample for UpdateTestCase", - "file": "dialogflow_v3_generated_test_cases_update_test_case_sync.py", + "description": "Sample for UpdateTool", + "file": "dialogflow_v3_generated_tools_update_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v3_generated_TestCases_UpdateTestCase_sync", + "regionTag": "dialogflow_v3_generated_Tools_UpdateTool_sync", "segments": [ { - "end": 54, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 56, "start": 27, "type": "SHORT" }, @@ -14909,22 +19274,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v3_generated_test_cases_update_test_case_sync.py" + "title": "dialogflow_v3_generated_tools_update_tool_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py index 5b2f5945c803..58f97502d816 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_agents.py @@ -1811,7 +1811,6 @@ def test_get_agent(request_type, transport: str = "grpc"): 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, @@ -1819,6 +1818,7 @@ def test_get_agent(request_type, transport: str = "grpc"): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) response = client.get_agent(request) @@ -1837,7 +1837,6 @@ def test_get_agent(request_type, transport: str = "grpc"): 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 @@ -1975,7 +1974,6 @@ async def test_get_agent_async( 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, @@ -2002,7 +2000,6 @@ async def test_get_agent_async( 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 @@ -2184,7 +2181,6 @@ def test_create_agent(request_type, transport: str = "grpc"): 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, @@ -2192,6 +2188,7 @@ def test_create_agent(request_type, transport: str = "grpc"): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) response = client.create_agent(request) @@ -2210,7 +2207,6 @@ def test_create_agent(request_type, transport: str = "grpc"): 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 @@ -2350,7 +2346,6 @@ async def test_create_agent_async( 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, @@ -2377,7 +2372,6 @@ async def test_create_agent_async( 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 @@ -2569,7 +2563,6 @@ def test_update_agent(request_type, transport: str = "grpc"): 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, @@ -2577,6 +2570,7 @@ def test_update_agent(request_type, transport: str = "grpc"): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) response = client.update_agent(request) @@ -2595,7 +2589,6 @@ def test_update_agent(request_type, transport: str = "grpc"): 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 @@ -2731,7 +2724,6 @@ async def test_update_agent_async( 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, @@ -2758,7 +2750,6 @@ async def test_update_agent_async( 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 @@ -7346,7 +7337,6 @@ async def test_get_agent_empty_call_grpc_asyncio(): 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, @@ -7387,7 +7377,6 @@ async def test_create_agent_empty_call_grpc_asyncio(): 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, @@ -7428,7 +7417,6 @@ async def test_update_agent_empty_call_grpc_asyncio(): 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, @@ -7815,7 +7803,6 @@ def test_get_agent_rest_call_success(request_type): 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, @@ -7823,6 +7810,7 @@ def test_get_agent_rest_call_success(request_type): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) # Wrap the value into a proper Response obj @@ -7846,7 +7834,6 @@ def test_get_agent_rest_call_success(request_type): 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 @@ -7964,6 +7951,7 @@ def test_create_agent_rest_call_success(request_type): "avatar_uri": "avatar_uri_value", "speech_to_text_settings": {"enable_speech_adaptation": True}, "start_flow": "start_flow_value", + "start_playbook": "start_playbook_value", "security_settings": "security_settings_value", "enable_stackdriver_logging": True, "enable_spell_correction": True, @@ -8091,7 +8079,6 @@ def get_message_fields(field): 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, @@ -8099,6 +8086,7 @@ def get_message_fields(field): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) # Wrap the value into a proper Response obj @@ -8122,7 +8110,6 @@ def get_message_fields(field): 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 @@ -8244,6 +8231,7 @@ def test_update_agent_rest_call_success(request_type): "avatar_uri": "avatar_uri_value", "speech_to_text_settings": {"enable_speech_adaptation": True}, "start_flow": "start_flow_value", + "start_playbook": "start_playbook_value", "security_settings": "security_settings_value", "enable_stackdriver_logging": True, "enable_spell_correction": True, @@ -8371,7 +8359,6 @@ def get_message_fields(field): 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, @@ -8379,6 +8366,7 @@ def get_message_fields(field): locked=True, satisfies_pzs=True, satisfies_pzi=True, + start_flow="start_flow_value", ) # Wrap the value into a proper Response obj @@ -8402,7 +8390,6 @@ def get_message_fields(field): 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 @@ -9258,9 +9245,13 @@ def test_update_generative_settings_rest_call_success(request_type): ], }, "generative_safety_settings": { + "default_banned_phrase_match_strategy": 1, "banned_phrases": [ {"text": "text_value", "language_code": "language_code_value"} - ] + ], + "rai_settings": {"category_filters": [{"category": 1, "filter_level": 1}]}, + "default_rai_settings": {}, + "prompt_security_settings": {"enable_prompt_security": True}, }, "knowledge_connector_settings": { "business": "business_value", @@ -9271,6 +9262,10 @@ def test_update_generative_settings_rest_call_success(request_type): "disable_data_store_fallback": True, }, "language_code": "language_code_value", + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10665,10 +10660,39 @@ def test_parse_flow_validation_result_path(): assert expected == actual -def test_secret_version_path(): +def test_playbook_path(): project = "cuttlefish" - secret = "mussel" - version = "winkle" + location = "mussel" + agent = "winkle" + playbook = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + actual = AgentsClient.playbook_path(project, location, agent, playbook) + assert expected == actual + + +def test_parse_playbook_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "playbook": "clam", + } + path = AgentsClient.playbook_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_playbook_path(path) + assert expected == actual + + +def test_secret_version_path(): + project = "whelk" + secret = "octopus" + version = "oyster" expected = "projects/{project}/secrets/{secret}/versions/{version}".format( project=project, secret=secret, @@ -10680,9 +10704,9 @@ def test_secret_version_path(): def test_parse_secret_version_path(): expected = { - "project": "nautilus", - "secret": "scallop", - "version": "abalone", + "project": "nudibranch", + "secret": "cuttlefish", + "version": "mussel", } path = AgentsClient.secret_version_path(**expected) @@ -10692,9 +10716,9 @@ def test_parse_secret_version_path(): def test_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" + project = "winkle" + location = "nautilus" + security_settings = "scallop" expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, @@ -10706,9 +10730,9 @@ def test_security_settings_path(): def test_parse_security_settings_path(): expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", + "project": "abalone", + "location": "squid", + "security_settings": "clam", } path = AgentsClient.security_settings_path(**expected) @@ -10718,7 +10742,7 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10728,7 +10752,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "octopus", } path = AgentsClient.common_billing_account_path(**expected) @@ -10738,7 +10762,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -10748,7 +10772,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "nudibranch", } path = AgentsClient.common_folder_path(**expected) @@ -10758,7 +10782,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -10768,7 +10792,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "mussel", } path = AgentsClient.common_organization_path(**expected) @@ -10778,7 +10802,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -10788,7 +10812,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nautilus", } path = AgentsClient.common_project_path(**expected) @@ -10798,8 +10822,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, @@ -10810,8 +10834,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "squid", + "location": "clam", } path = AgentsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_environments.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_environments.py index 115491a6640a..2b8283fb95b8 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_environments.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_environments.py @@ -7513,7 +7513,9 @@ def test_create_environment_rest_call_success(request_type): "uri": "uri_value", "username": "username_value", "password": "password_value", + "secret_version_for_username_password": "secret_version_for_username_password_value", "request_headers": {}, + "secret_versions_for_request_headers": {}, "allowed_ca_certs": [ b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2", @@ -7521,10 +7523,14 @@ def test_create_environment_rest_call_success(request_type): "oauth_config": { "client_id": "client_id_value", "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", "token_endpoint": "token_endpoint_value", "scopes": ["scopes_value1", "scopes_value2"], }, "service_agent_auth": 1, + "service_account_auth_config": { + "service_account": "service_account_value" + }, "webhook_type": 1, "http_method": 1, "request_body": "request_body_value", @@ -7758,7 +7764,9 @@ def test_update_environment_rest_call_success(request_type): "uri": "uri_value", "username": "username_value", "password": "password_value", + "secret_version_for_username_password": "secret_version_for_username_password_value", "request_headers": {}, + "secret_versions_for_request_headers": {}, "allowed_ca_certs": [ b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2", @@ -7766,10 +7774,14 @@ def test_update_environment_rest_call_success(request_type): "oauth_config": { "client_id": "client_id_value", "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", "token_endpoint": "token_endpoint_value", "scopes": ["scopes_value1", "scopes_value2"], }, "service_agent_auth": 1, + "service_account_auth_config": { + "service_account": "service_account_value" + }, "webhook_type": 1, "http_method": 1, "request_body": "request_body_value", @@ -9659,11 +9671,37 @@ def test_parse_environment_path(): assert expected == actual -def test_service_path(): +def test_secret_version_path(): project = "cuttlefish" - location = "mussel" - namespace = "winkle" - service = "nautilus" + secret = "mussel" + version = "winkle" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + actual = EnvironmentsClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "nautilus", + "secret": "scallop", + "version": "abalone", + } + path = EnvironmentsClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_secret_version_path(path) + assert expected == actual + + +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, @@ -9676,10 +9714,10 @@ def test_service_path(): def test_parse_service_path(): expected = { - "project": "scallop", - "location": "abalone", - "namespace": "squid", - "service": "clam", + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", } path = EnvironmentsClient.service_path(**expected) @@ -9689,10 +9727,10 @@ def test_parse_service_path(): def test_test_case_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - test_case = "nudibranch" + project = "winkle" + location = "nautilus" + agent = "scallop" + test_case = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( project=project, location=location, @@ -9705,10 +9743,10 @@ def test_test_case_path(): def test_parse_test_case_path(): expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "test_case": "nautilus", + "project": "squid", + "location": "clam", + "agent": "whelk", + "test_case": "octopus", } path = EnvironmentsClient.test_case_path(**expected) @@ -9718,11 +9756,11 @@ def test_parse_test_case_path(): def test_test_case_result_path(): - project = "scallop" - location = "abalone" - agent = "squid" - test_case = "clam" - result = "whelk" + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + test_case = "mussel" + result = "winkle" expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -9738,11 +9776,11 @@ def test_test_case_result_path(): def test_parse_test_case_result_path(): expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "test_case": "cuttlefish", - "result": "mussel", + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "test_case": "squid", + "result": "clam", } path = EnvironmentsClient.test_case_result_path(**expected) @@ -9752,11 +9790,11 @@ def test_parse_test_case_result_path(): def test_version_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - version = "squid" + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" + version = "cuttlefish" expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, @@ -9770,11 +9808,11 @@ def test_version_path(): def test_parse_version_path(): expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "flow": "oyster", - "version": "nudibranch", + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "flow": "scallop", + "version": "abalone", } path = EnvironmentsClient.version_path(**expected) @@ -9784,10 +9822,10 @@ def test_parse_version_path(): def test_webhook_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - webhook = "nautilus" + project = "squid" + location = "clam" + agent = "whelk" + webhook = "octopus" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -9800,10 +9838,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "scallop", - "location": "abalone", - "agent": "squid", - "webhook": "clam", + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "webhook": "mussel", } path = EnvironmentsClient.webhook_path(**expected) @@ -9813,7 +9851,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -9823,7 +9861,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -9833,7 +9871,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -9843,7 +9881,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = EnvironmentsClient.common_folder_path(**expected) @@ -9853,7 +9891,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -9863,7 +9901,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = EnvironmentsClient.common_organization_path(**expected) @@ -9873,7 +9911,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -9883,7 +9921,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = EnvironmentsClient.common_project_path(**expected) @@ -9893,8 +9931,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -9905,8 +9943,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = EnvironmentsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_examples.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_examples.py new file mode 100644 index 000000000000..d65642d541a6 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_examples.py @@ -0,0 +1,7280 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.examples import ( + ExamplesAsyncClient, + ExamplesClient, + pagers, + transports, +) +from google.cloud.dialogflowcx_v3.types import example +from google.cloud.dialogflowcx_v3.types import example as gcdc_example +from google.cloud.dialogflowcx_v3.types import trace + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# 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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +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 ExamplesClient._get_default_mtls_endpoint(None) is None + assert ExamplesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + ExamplesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ExamplesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ExamplesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ExamplesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert ExamplesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ExamplesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ExamplesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + ExamplesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ExamplesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ExamplesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ExamplesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ExamplesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ExamplesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ExamplesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert ExamplesClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ExamplesClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert ExamplesClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert ExamplesClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + ExamplesClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert ExamplesClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ExamplesClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ExamplesClient._get_client_cert_source(None, False) is None + assert ( + ExamplesClient._get_client_cert_source(mock_provided_cert_source, False) is None + ) + assert ( + ExamplesClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ExamplesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ExamplesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ExamplesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesClient), +) +@mock.patch.object( + ExamplesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ExamplesClient._DEFAULT_UNIVERSE + default_endpoint = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ExamplesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ExamplesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ExamplesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ExamplesClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ExamplesClient._get_api_endpoint(None, None, default_universe, "always") + == ExamplesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ExamplesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ExamplesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ExamplesClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ExamplesClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ExamplesClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ExamplesClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + ExamplesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ExamplesClient._get_universe_domain(None, None) + == ExamplesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ExamplesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ExamplesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ExamplesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ExamplesClient, "grpc"), + (ExamplesAsyncClient, "grpc_asyncio"), + (ExamplesClient, "rest"), + ], +) +def test_examples_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ExamplesGrpcTransport, "grpc"), + (transports.ExamplesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ExamplesRestTransport, "rest"), + ], +) +def test_examples_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ExamplesClient, "grpc"), + (ExamplesAsyncClient, "grpc_asyncio"), + (ExamplesClient, "rest"), + ], +) +def test_examples_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_examples_client_get_transport_class(): + transport = ExamplesClient.get_transport_class() + available_transports = [ + transports.ExamplesGrpcTransport, + transports.ExamplesRestTransport, + ] + assert transport in available_transports + + transport = ExamplesClient.get_transport_class("grpc") + assert transport == transports.ExamplesGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc"), + (ExamplesAsyncClient, transports.ExamplesGrpcAsyncIOTransport, "grpc_asyncio"), + (ExamplesClient, transports.ExamplesRestTransport, "rest"), + ], +) +@mock.patch.object( + ExamplesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesClient), +) +@mock.patch.object( + ExamplesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesAsyncClient), +) +def test_examples_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(ExamplesClient, "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(ExamplesClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc", "true"), + ( + ExamplesAsyncClient, + transports.ExamplesGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc", "false"), + ( + ExamplesAsyncClient, + transports.ExamplesGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ExamplesClient, transports.ExamplesRestTransport, "rest", "true"), + (ExamplesClient, transports.ExamplesRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ExamplesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesClient), +) +@mock.patch.object( + ExamplesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_examples_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ExamplesClient, ExamplesAsyncClient]) +@mock.patch.object( + ExamplesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExamplesClient) +) +@mock.patch.object( + ExamplesAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ExamplesAsyncClient), +) +def test_examples_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [ExamplesClient, ExamplesAsyncClient]) +@mock.patch.object( + ExamplesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesClient), +) +@mock.patch.object( + ExamplesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ExamplesAsyncClient), +) +def test_examples_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ExamplesClient._DEFAULT_UNIVERSE + default_endpoint = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ExamplesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc"), + (ExamplesAsyncClient, transports.ExamplesGrpcAsyncIOTransport, "grpc_asyncio"), + (ExamplesClient, transports.ExamplesRestTransport, "rest"), + ], +) +def test_examples_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc", grpc_helpers), + ( + ExamplesAsyncClient, + transports.ExamplesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ExamplesClient, transports.ExamplesRestTransport, "rest", None), + ], +) +def test_examples_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_examples_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3.services.examples.transports.ExamplesGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ExamplesClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ExamplesClient, transports.ExamplesGrpcTransport, "grpc", grpc_helpers), + ( + ExamplesAsyncClient, + transports.ExamplesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_examples_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_example.CreateExampleRequest, + dict, + ], +) +def test_create_example(request_type, transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + response = client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_example.CreateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +def test_create_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_example.CreateExampleRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_example.CreateExampleRequest( + parent="parent_value", + ) + + +def test_create_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_example] = mock_rpc + request = {} + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_example + ] = mock_rpc + + request = {} + await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_example_async( + transport: str = "grpc_asyncio", request_type=gcdc_example.CreateExampleRequest +): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + response = await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_example.CreateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_create_example_async_from_dict(): + await test_create_example_async(request_type=dict) + + +def test_create_example_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_example.CreateExampleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = gcdc_example.Example() + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_example_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_example.CreateExampleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example() + ) + await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_example_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_example( + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].example + mock_val = gcdc_example.Example(name="name_value") + assert arg == mock_val + + +def test_create_example_flattened_error(): + client = ExamplesClient( + credentials=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_example( + gcdc_example.CreateExampleRequest(), + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_example_flattened_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_example( + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].example + mock_val = gcdc_example.Example(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_example_flattened_error_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_example( + gcdc_example.CreateExampleRequest(), + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + example.DeleteExampleRequest, + dict, + ], +) +def test_delete_example(request_type, transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = example.DeleteExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = example.DeleteExampleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == example.DeleteExampleRequest( + name="name_value", + ) + + +def test_delete_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_example] = mock_rpc + request = {} + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_example + ] = mock_rpc + + request = {} + await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_example_async( + transport: str = "grpc_asyncio", request_type=example.DeleteExampleRequest +): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = example.DeleteExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_example_async_from_dict(): + await test_delete_example_async(request_type=dict) + + +def test_delete_example_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.DeleteExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = None + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_example_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.DeleteExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_example_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__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_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_example_flattened_error(): + client = ExamplesClient( + credentials=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_example( + example.DeleteExampleRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_example_flattened_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__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_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_example_flattened_error_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_example( + example.DeleteExampleRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + example.ListExamplesRequest, + dict, + ], +) +def test_list_examples(request_type, transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = example.ListExamplesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_examples_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = example.ListExamplesRequest( + parent="parent_value", + page_token="page_token_value", + language_code="language_code_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_examples(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == example.ListExamplesRequest( + parent="parent_value", + page_token="page_token_value", + language_code="language_code_value", + ) + + +def test_list_examples_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_examples in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_examples] = mock_rpc + request = {} + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_examples_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_examples + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_examples + ] = mock_rpc + + request = {} + await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_examples_async( + transport: str = "grpc_asyncio", request_type=example.ListExamplesRequest +): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = example.ListExamplesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_examples_async_from_dict(): + await test_list_examples_async(request_type=dict) + + +def test_list_examples_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.ListExamplesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = example.ListExamplesResponse() + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_examples_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.ListExamplesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.ListExamplesResponse() + ) + await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_examples_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.ListExamplesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_examples( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_examples_flattened_error(): + client = ExamplesClient( + credentials=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_examples( + example.ListExamplesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_examples_flattened_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.ListExamplesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.ListExamplesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_examples( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_examples_flattened_error_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_examples( + example.ListExamplesRequest(), + parent="parent_value", + ) + + +def test_list_examples_pager(transport_name: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + example.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_examples(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, example.Example) for i in results) + + +def test_list_examples_pages(transport_name: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + example.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + pages = list(client.list_examples(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_examples_async_pager(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + example.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_examples( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, example.Example) for i in responses) + + +@pytest.mark.asyncio +async def test_list_examples_async_pages(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + example.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_examples(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + example.GetExampleRequest, + dict, + ], +) +def test_get_example(request_type, transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + response = client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = example.GetExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +def test_get_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = example.GetExampleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == example.GetExampleRequest( + name="name_value", + ) + + +def test_get_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_example] = mock_rpc + request = {} + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_example + ] = mock_rpc + + request = {} + await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_example_async( + transport: str = "grpc_asyncio", request_type=example.GetExampleRequest +): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + response = await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = example.GetExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_get_example_async_from_dict(): + await test_get_example_async(request_type=dict) + + +def test_get_example_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.GetExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = example.Example() + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_example_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = example.GetExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(example.Example()) + await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_example_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_example_flattened_error(): + client = ExamplesClient( + credentials=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_example( + example.GetExampleRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_example_flattened_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(example.Example()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_example_flattened_error_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_example( + example.GetExampleRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_example.UpdateExampleRequest, + dict, + ], +) +def test_update_example(request_type, transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + response = client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_example.UpdateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +def test_update_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_example.UpdateExampleRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_example.UpdateExampleRequest() + + +def test_update_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_example] = mock_rpc + request = {} + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_example + ] = mock_rpc + + request = {} + await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_example_async( + transport: str = "grpc_asyncio", request_type=gcdc_example.UpdateExampleRequest +): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + response = await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_example.UpdateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_update_example_async_from_dict(): + await test_update_example_async(request_type=dict) + + +def test_update_example_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_example.UpdateExampleRequest() + + request.example.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = gcdc_example.Example() + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "example.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_example_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_example.UpdateExampleRequest() + + request.example.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example() + ) + await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "example.name=name_value", + ) in kw["metadata"] + + +def test_update_example_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_example( + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].example + mock_val = gcdc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_example_flattened_error(): + client = ExamplesClient( + credentials=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_example( + gcdc_example.UpdateExampleRequest(), + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_example_flattened_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_example( + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].example + mock_val = gcdc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_example_flattened_error_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_example( + gcdc_example.UpdateExampleRequest(), + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_create_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_example] = mock_rpc + + request = {} + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_example_rest_required_fields( + request_type=gcdc_example.CreateExampleRequest, +): + transport_class = transports.ExamplesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_example_rest_unset_required_fields(): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_example._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "example", + ) + ) + ) + + +def test_create_example_rest_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples" + % client.transport._host, + args[1], + ) + + +def test_create_example_rest_flattened_error(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_example( + gcdc_example.CreateExampleRequest(), + parent="parent_value", + example=gcdc_example.Example(name="name_value"), + ) + + +def test_delete_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_example] = mock_rpc + + request = {} + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_example_rest_required_fields(request_type=example.DeleteExampleRequest): + transport_class = transports.ExamplesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_example_rest_unset_required_fields(): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_example_rest_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_example_rest_flattened_error(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_example( + example.DeleteExampleRequest(), + name="name_value", + ) + + +def test_list_examples_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_examples in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_examples] = mock_rpc + + request = {} + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_examples_rest_required_fields(request_type=example.ListExamplesRequest): + transport_class = transports.ExamplesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_examples._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_examples._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "language_code", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = example.ListExamplesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_examples(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_examples_rest_unset_required_fields(): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_examples._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "languageCode", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_examples_rest_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.ListExamplesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = example.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_examples(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/examples" + % client.transport._host, + args[1], + ) + + +def test_list_examples_rest_flattened_error(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_examples( + example.ListExamplesRequest(), + parent="parent_value", + ) + + +def test_list_examples_rest_pager(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + example.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + example.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(example.ListExamplesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + pager = client.list_examples(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, example.Example) for i in results) + + pages = list(client.list_examples(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_example] = mock_rpc + + request = {} + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_example_rest_required_fields(request_type=example.GetExampleRequest): + transport_class = transports.ExamplesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_example_rest_unset_required_fields(): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_example_rest_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_get_example_rest_flattened_error(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_example( + example.GetExampleRequest(), + name="name_value", + ) + + +def test_update_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_example] = mock_rpc + + request = {} + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_example_rest_required_fields( + request_type=gcdc_example.UpdateExampleRequest, +): + transport_class = transports.ExamplesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_example._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_example_rest_unset_required_fields(): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("example",))) + + +def test_update_example_rest_flattened(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = { + "example": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{example.name=projects/*/locations/*/agents/*/playbooks/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_update_example_rest_flattened_error(transport: str = "rest"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_example( + gcdc_example.UpdateExampleRequest(), + example=gcdc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExamplesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ExamplesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ExamplesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExamplesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ExamplesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExamplesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExamplesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExamplesGrpcTransport, + transports.ExamplesGrpcAsyncIOTransport, + transports.ExamplesRestTransport, + ], +) +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_kind_grpc(): + transport = ExamplesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_example_empty_call_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = gcdc_example.Example() + client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_example_empty_call_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = None + client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_examples_empty_call_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = example.ListExamplesResponse() + client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_example_empty_call_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = example.Example() + client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_example_empty_call_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = gcdc_example.Example() + client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.UpdateExampleRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ExamplesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_example_empty_call_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + await client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_example_empty_call_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_examples_empty_call_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_example_empty_call_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + await client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_example_empty_call_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + ) + await client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.UpdateExampleRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ExamplesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_example_rest_bad_request( + request_type=gcdc_example.CreateExampleRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_example.CreateExampleRequest, + dict, + ], +) +def test_create_example_rest_call_success(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request_init["example"] = { + "name": "name_value", + "playbook_input": { + "preceding_conversation_summary": "preceding_conversation_summary_value" + }, + "playbook_output": {"execution_summary": "execution_summary_value"}, + "actions": [ + { + "user_utterance": {"text": "text_value"}, + "agent_utterance": {"text": "text_value"}, + "tool_use": { + "tool": "tool_value", + "display_name": "display_name_value", + "action": "action_value", + "input_action_parameters": {"fields": {}}, + "output_action_parameters": {}, + }, + "playbook_invocation": { + "playbook": "playbook_value", + "display_name": "display_name_value", + "playbook_input": {}, + "playbook_output": {}, + "playbook_state": 1, + }, + "flow_invocation": { + "flow": "flow_value", + "display_name": "display_name_value", + "flow_state": 1, + }, + "playbook_transition": { + "playbook": "playbook_value", + "display_name": "display_name_value", + }, + "flow_transition": { + "flow": "flow_value", + "display_name": "display_name_value", + }, + } + ], + "display_name": "display_name_value", + "description": "description_value", + "token_count": 1193, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "conversation_state": 1, + "language_code": "language_code_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_example.CreateExampleRequest.meta.fields["example"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["example"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["example"][field])): + del request_init["example"][field][i][subfield] + else: + del request_init["example"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_example_rest_interceptors(null_interceptor): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(), + ) + client = ExamplesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ExamplesRestInterceptor, "post_create_example" + ) as post, mock.patch.object( + transports.ExamplesRestInterceptor, "post_create_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ExamplesRestInterceptor, "pre_create_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_example.CreateExampleRequest.pb( + gcdc_example.CreateExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_example.Example.to_json(gcdc_example.Example()) + req.return_value.content = return_value + + request = gcdc_example.CreateExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_example.Example() + post_with_metadata.return_value = gcdc_example.Example(), metadata + + client.create_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_example_rest_bad_request(request_type=example.DeleteExampleRequest): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + example.DeleteExampleRequest, + dict, + ], +) +def test_delete_example_rest_call_success(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_example(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_example_rest_interceptors(null_interceptor): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(), + ) + client = ExamplesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ExamplesRestInterceptor, "pre_delete_example" + ) as pre: + pre.assert_not_called() + pb_message = example.DeleteExampleRequest.pb(example.DeleteExampleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = example.DeleteExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_examples_rest_bad_request(request_type=example.ListExamplesRequest): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_examples(request) + + +@pytest.mark.parametrize( + "request_type", + [ + example.ListExamplesRequest, + dict, + ], +) +def test_list_examples_rest_call_success(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_examples(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_examples_rest_interceptors(null_interceptor): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(), + ) + client = ExamplesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ExamplesRestInterceptor, "post_list_examples" + ) as post, mock.patch.object( + transports.ExamplesRestInterceptor, "post_list_examples_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ExamplesRestInterceptor, "pre_list_examples" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = example.ListExamplesRequest.pb(example.ListExamplesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = example.ListExamplesResponse.to_json( + example.ListExamplesResponse() + ) + req.return_value.content = return_value + + request = example.ListExamplesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = example.ListExamplesResponse() + post_with_metadata.return_value = example.ListExamplesResponse(), metadata + + client.list_examples( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_example_rest_bad_request(request_type=example.GetExampleRequest): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + example.GetExampleRequest, + dict, + ], +) +def test_get_example_rest_call_success(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_example_rest_interceptors(null_interceptor): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(), + ) + client = ExamplesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ExamplesRestInterceptor, "post_get_example" + ) as post, mock.patch.object( + transports.ExamplesRestInterceptor, "post_get_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ExamplesRestInterceptor, "pre_get_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = example.GetExampleRequest.pb(example.GetExampleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = example.Example.to_json(example.Example()) + req.return_value.content = return_value + + request = example.GetExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = example.Example() + post_with_metadata.return_value = example.Example(), metadata + + client.get_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_example_rest_bad_request( + request_type=gcdc_example.UpdateExampleRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "example": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_example.UpdateExampleRequest, + dict, + ], +) +def test_update_example_rest_call_success(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "example": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5" + } + } + request_init["example"] = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/examples/sample5", + "playbook_input": { + "preceding_conversation_summary": "preceding_conversation_summary_value" + }, + "playbook_output": {"execution_summary": "execution_summary_value"}, + "actions": [ + { + "user_utterance": {"text": "text_value"}, + "agent_utterance": {"text": "text_value"}, + "tool_use": { + "tool": "tool_value", + "display_name": "display_name_value", + "action": "action_value", + "input_action_parameters": {"fields": {}}, + "output_action_parameters": {}, + }, + "playbook_invocation": { + "playbook": "playbook_value", + "display_name": "display_name_value", + "playbook_input": {}, + "playbook_output": {}, + "playbook_state": 1, + }, + "flow_invocation": { + "flow": "flow_value", + "display_name": "display_name_value", + "flow_state": 1, + }, + "playbook_transition": { + "playbook": "playbook_value", + "display_name": "display_name_value", + }, + "flow_transition": { + "flow": "flow_value", + "display_name": "display_name_value", + }, + } + ], + "display_name": "display_name_value", + "description": "description_value", + "token_count": 1193, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "conversation_state": 1, + "language_code": "language_code_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_example.UpdateExampleRequest.meta.fields["example"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["example"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["example"][field])): + del request_init["example"][field][i][subfield] + else: + del request_init["example"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + token_count=1193, + conversation_state=trace.OutputState.OUTPUT_STATE_OK, + language_code="language_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.token_count == 1193 + assert response.conversation_state == trace.OutputState.OUTPUT_STATE_OK + assert response.language_code == "language_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_example_rest_interceptors(null_interceptor): + transport = transports.ExamplesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ExamplesRestInterceptor(), + ) + client = ExamplesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ExamplesRestInterceptor, "post_update_example" + ) as post, mock.patch.object( + transports.ExamplesRestInterceptor, "post_update_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ExamplesRestInterceptor, "pre_update_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_example.UpdateExampleRequest.pb( + gcdc_example.UpdateExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_example.Example.to_json(gcdc_example.Example()) + req.return_value.content = return_value + + request = gcdc_example.UpdateExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_example.Example() + post_with_metadata.return_value = gcdc_example.Example(), metadata + + client.update_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_example_empty_call_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_example_empty_call_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_examples_empty_call_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_example_empty_call_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = example.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_example_empty_call_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_example.UpdateExampleRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ExamplesGrpcTransport, + ) + + +def test_examples_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ExamplesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_examples_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3.services.examples.transports.ExamplesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ExamplesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_example", + "delete_example", + "list_examples", + "get_example", + "update_example", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_examples_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.examples.transports.ExamplesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExamplesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_examples_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.examples.transports.ExamplesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExamplesTransport() + adc.assert_called_once() + + +def test_examples_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) + ExamplesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExamplesGrpcTransport, + transports.ExamplesGrpcAsyncIOTransport, + ], +) +def test_examples_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.ExamplesGrpcTransport, + transports.ExamplesGrpcAsyncIOTransport, + transports.ExamplesRestTransport, + ], +) +def test_examples_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExamplesGrpcTransport, grpc_helpers), + (transports.ExamplesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_examples_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ExamplesGrpcTransport, transports.ExamplesGrpcAsyncIOTransport], +) +def test_examples_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_examples_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ExamplesRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_examples_host_no_port(transport_name): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_examples_host_with_port(transport_name): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_examples_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ExamplesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ExamplesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_example._session + session2 = client2.transport.create_example._session + assert session1 != session2 + session1 = client1.transport.delete_example._session + session2 = client2.transport.delete_example._session + assert session1 != session2 + session1 = client1.transport.list_examples._session + session2 = client2.transport.list_examples._session + assert session1 != session2 + session1 = client1.transport.get_example._session + session2 = client2.transport.get_example._session + assert session1 != session2 + session1 = client1.transport.update_example._session + session2 = client2.transport.update_example._session + assert session1 != session2 + + +def test_examples_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExamplesGrpcTransport( + 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_examples_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExamplesGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.ExamplesGrpcTransport, transports.ExamplesGrpcAsyncIOTransport], +) +def test_examples_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.ExamplesGrpcTransport, transports.ExamplesGrpcAsyncIOTransport], +) +def test_examples_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_example_path(): + project = "squid" + location = "clam" + agent = "whelk" + playbook = "octopus" + example = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/examples/{example}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + example=example, + ) + actual = ExamplesClient.example_path(project, location, agent, playbook, example) + assert expected == actual + + +def test_parse_example_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "playbook": "winkle", + "example": "nautilus", + } + path = ExamplesClient.example_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_example_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 = ExamplesClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "flow": "nudibranch", + } + path = ExamplesClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_flow_path(path) + assert expected == actual + + +def test_playbook_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + playbook = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + actual = ExamplesClient.playbook_path(project, location, agent, playbook) + assert expected == actual + + +def test_parse_playbook_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "playbook": "clam", + } + path = ExamplesClient.playbook_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_playbook_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + tool = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = ExamplesClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "tool": "nautilus", + } + path = ExamplesClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_tool_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ExamplesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = ExamplesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ExamplesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = ExamplesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ExamplesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = ExamplesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = ExamplesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = ExamplesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.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 = ExamplesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = ExamplesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExamplesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ExamplesTransport, "_prep_wrapped_messages" + ) as prep: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ExamplesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ExamplesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = ExamplesClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = ExamplesAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ExamplesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = ExamplesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ExamplesClient, transports.ExamplesGrpcTransport), + (ExamplesAsyncClient, transports.ExamplesGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py index 6165432e3895..09edb4d55523 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_flows.py @@ -80,7 +80,9 @@ gcs, import_strategy, page, + parameter_definition, response_message, + tool_call, validation_message, ) from google.cloud.dialogflowcx_v3.types import flow @@ -6934,6 +6936,11 @@ def test_create_flow_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -7007,6 +7014,7 @@ def test_create_flow_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], "transition_route_groups": [ @@ -7032,6 +7040,21 @@ def test_create_flow_rest_call_success(request_type): } ], }, + "input_parameter_definitions": [ + { + "name": "name_value", + "type_": 1, + "type_schema": { + "inline_schema": {"type_": 1, "items": {}}, + "schema_reference": { + "tool": "tool_value", + "schema": "schema_value", + }, + }, + "description": "description_value", + } + ], + "output_parameter_definitions": {}, "multi_language_settings": { "enable_multi_language_detection": True, "supported_response_language_codes": [ @@ -7649,6 +7672,11 @@ def test_update_flow_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -7722,6 +7750,7 @@ def test_update_flow_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], "transition_route_groups": [ @@ -7747,6 +7776,21 @@ def test_update_flow_rest_call_success(request_type): } ], }, + "input_parameter_definitions": [ + { + "name": "name_value", + "type_": 1, + "type_schema": { + "inline_schema": {"type_": 1, "items": {}}, + "schema_reference": { + "tool": "tool_value", + "schema": "schema_value", + }, + }, + "description": "description_value", + } + ], + "output_parameter_definitions": {}, "multi_language_settings": { "enable_multi_language_detection": True, "supported_response_language_codes": [ @@ -9713,12 +9757,72 @@ def test_parse_page_path(): assert expected == actual -def test_transition_route_group_path(): +def test_playbook_path(): project = "cuttlefish" location = "mussel" agent = "winkle" - flow = "nautilus" - transition_route_group = "scallop" + playbook = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + actual = FlowsClient.playbook_path(project, location, agent, playbook) + assert expected == actual + + +def test_parse_playbook_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "playbook": "clam", + } + path = FlowsClient.playbook_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_playbook_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + tool = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = FlowsClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "tool": "nautilus", + } + path = FlowsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_tool_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, @@ -9734,11 +9838,11 @@ def test_transition_route_group_path(): def test_parse_transition_route_group_path(): expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "flow": "whelk", - "transition_route_group": "octopus", + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", } path = FlowsClient.transition_route_group_path(**expected) @@ -9748,10 +9852,10 @@ def test_parse_transition_route_group_path(): def test_webhook_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - webhook = "mussel" + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -9764,10 +9868,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "webhook": "abalone", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = FlowsClient.webhook_path(**expected) @@ -9777,7 +9881,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -9787,7 +9891,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nudibranch", } path = FlowsClient.common_billing_account_path(**expected) @@ -9797,7 +9901,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -9807,7 +9911,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "mussel", } path = FlowsClient.common_folder_path(**expected) @@ -9817,7 +9921,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -9827,7 +9931,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "nautilus", } path = FlowsClient.common_organization_path(**expected) @@ -9837,7 +9941,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -9847,7 +9951,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "abalone", } path = FlowsClient.common_project_path(**expected) @@ -9857,8 +9961,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -9869,8 +9973,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "whelk", + "location": "octopus", } path = FlowsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_generators.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_generators.py index 288672b14595..04d5337eefcb 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_generators.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_generators.py @@ -61,6 +61,7 @@ pagers, transports, ) +from google.cloud.dialogflowcx_v3.types import generative_settings from google.cloud.dialogflowcx_v3.types import generator from google.cloud.dialogflowcx_v3.types import generator as gcdc_generator @@ -4782,6 +4783,10 @@ def test_create_generator_rest_call_success(request_type): "display_name": "display_name_value", "prompt_text": {"text": "text_value"}, "placeholders": [{"id": "id_value", "name": "name_value"}], + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, "model_parameter": { "temperature": 0.1198, "max_decode_steps": 1687, @@ -4998,6 +5003,10 @@ def test_update_generator_rest_call_success(request_type): "display_name": "display_name_value", "prompt_text": {"text": "text_value"}, "placeholders": [{"id": "id_value", "name": "name_value"}], + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, "model_parameter": { "temperature": 0.1198, "max_decode_steps": 1687, diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py index 46d1b5360d0f..743dd687034d 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_pages.py @@ -71,7 +71,7 @@ ) 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.cloud.dialogflowcx_v3.types import response_message, tool_call CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -4796,6 +4796,11 @@ def test_create_page_rest_call_success(request_type): }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -4872,6 +4877,7 @@ def test_create_page_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], }, @@ -5149,6 +5155,11 @@ def test_update_page_rest_call_success(request_type): }, "telephony_transfer_call": {"phone_number": "phone_number_value"}, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -5225,6 +5236,7 @@ def test_update_page_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], }, @@ -6536,12 +6548,72 @@ def test_parse_page_path(): assert expected == actual -def test_transition_route_group_path(): +def test_playbook_path(): project = "cuttlefish" location = "mussel" agent = "winkle" - flow = "nautilus" - transition_route_group = "scallop" + playbook = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + actual = PagesClient.playbook_path(project, location, agent, playbook) + assert expected == actual + + +def test_parse_playbook_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "playbook": "clam", + } + path = PagesClient.playbook_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_playbook_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + tool = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = PagesClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "tool": "nautilus", + } + path = PagesClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_tool_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, @@ -6557,11 +6629,11 @@ def test_transition_route_group_path(): def test_parse_transition_route_group_path(): expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "flow": "whelk", - "transition_route_group": "octopus", + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", } path = PagesClient.transition_route_group_path(**expected) @@ -6571,10 +6643,10 @@ def test_parse_transition_route_group_path(): def test_webhook_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - webhook = "mussel" + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -6587,10 +6659,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "webhook": "abalone", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = PagesClient.webhook_path(**expected) @@ -6600,7 +6672,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6610,7 +6682,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nudibranch", } path = PagesClient.common_billing_account_path(**expected) @@ -6620,7 +6692,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -6630,7 +6702,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "mussel", } path = PagesClient.common_folder_path(**expected) @@ -6640,7 +6712,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -6650,7 +6722,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "nautilus", } path = PagesClient.common_organization_path(**expected) @@ -6660,7 +6732,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -6670,7 +6742,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "abalone", } path = PagesClient.common_project_path(**expected) @@ -6680,8 +6752,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -6692,8 +6764,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "whelk", + "location": "octopus", } path = PagesClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_playbooks.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_playbooks.py new file mode 100644 index 000000000000..23f2ef4bed0a --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_playbooks.py @@ -0,0 +1,13060 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.playbooks import ( + PlaybooksAsyncClient, + PlaybooksClient, + pagers, + transports, +) +from google.cloud.dialogflowcx_v3.types import ( + advanced_settings, + code_block, + example, + fulfillment, + gcs, + generative_settings, + import_strategy, + parameter_definition, +) +from google.cloud.dialogflowcx_v3.types import response_message, tool_call, trace +from google.cloud.dialogflowcx_v3.types import playbook +from google.cloud.dialogflowcx_v3.types import playbook as gcdc_playbook + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# 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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +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 PlaybooksClient._get_default_mtls_endpoint(None) is None + assert PlaybooksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + PlaybooksClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + PlaybooksClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PlaybooksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert PlaybooksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert PlaybooksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert PlaybooksClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert PlaybooksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + PlaybooksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert PlaybooksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert PlaybooksClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert PlaybooksClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert PlaybooksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + PlaybooksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert PlaybooksClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert PlaybooksClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert PlaybooksClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert PlaybooksClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert PlaybooksClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + PlaybooksClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert PlaybooksClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert PlaybooksClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert PlaybooksClient._get_client_cert_source(None, False) is None + assert ( + PlaybooksClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + PlaybooksClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + PlaybooksClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + PlaybooksClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + PlaybooksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksClient), +) +@mock.patch.object( + PlaybooksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = PlaybooksClient._DEFAULT_UNIVERSE + default_endpoint = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + PlaybooksClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + PlaybooksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == PlaybooksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PlaybooksClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + PlaybooksClient._get_api_endpoint(None, None, default_universe, "always") + == PlaybooksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PlaybooksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == PlaybooksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PlaybooksClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + PlaybooksClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + PlaybooksClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + PlaybooksClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + PlaybooksClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + PlaybooksClient._get_universe_domain(None, None) + == PlaybooksClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + PlaybooksClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = PlaybooksClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = PlaybooksClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (PlaybooksClient, "grpc"), + (PlaybooksAsyncClient, "grpc_asyncio"), + (PlaybooksClient, "rest"), + ], +) +def test_playbooks_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.PlaybooksGrpcTransport, "grpc"), + (transports.PlaybooksGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PlaybooksRestTransport, "rest"), + ], +) +def test_playbooks_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (PlaybooksClient, "grpc"), + (PlaybooksAsyncClient, "grpc_asyncio"), + (PlaybooksClient, "rest"), + ], +) +def test_playbooks_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_playbooks_client_get_transport_class(): + transport = PlaybooksClient.get_transport_class() + available_transports = [ + transports.PlaybooksGrpcTransport, + transports.PlaybooksRestTransport, + ] + assert transport in available_transports + + transport = PlaybooksClient.get_transport_class("grpc") + assert transport == transports.PlaybooksGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc"), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (PlaybooksClient, transports.PlaybooksRestTransport, "rest"), + ], +) +@mock.patch.object( + PlaybooksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksClient), +) +@mock.patch.object( + PlaybooksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksAsyncClient), +) +def test_playbooks_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(PlaybooksClient, "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(PlaybooksClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc", "true"), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc", "false"), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (PlaybooksClient, transports.PlaybooksRestTransport, "rest", "true"), + (PlaybooksClient, transports.PlaybooksRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + PlaybooksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksClient), +) +@mock.patch.object( + PlaybooksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_playbooks_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [PlaybooksClient, PlaybooksAsyncClient]) +@mock.patch.object( + PlaybooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlaybooksClient) +) +@mock.patch.object( + PlaybooksAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PlaybooksAsyncClient), +) +def test_playbooks_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [PlaybooksClient, PlaybooksAsyncClient]) +@mock.patch.object( + PlaybooksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksClient), +) +@mock.patch.object( + PlaybooksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PlaybooksAsyncClient), +) +def test_playbooks_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = PlaybooksClient._DEFAULT_UNIVERSE + default_endpoint = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = PlaybooksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc"), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (PlaybooksClient, transports.PlaybooksRestTransport, "rest"), + ], +) +def test_playbooks_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc", grpc_helpers), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (PlaybooksClient, transports.PlaybooksRestTransport, "rest", None), + ], +) +def test_playbooks_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_playbooks_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3.services.playbooks.transports.PlaybooksGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = PlaybooksClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport, "grpc", grpc_helpers), + ( + PlaybooksAsyncClient, + transports.PlaybooksGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_playbooks_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_playbook.CreatePlaybookRequest, + dict, + ], +) +def test_create_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + response = client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_playbook.CreatePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +def test_create_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_playbook.CreatePlaybookRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_playbook.CreatePlaybookRequest( + parent="parent_value", + ) + + +def test_create_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_playbook] = mock_rpc + request = {} + client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_playbook + ] = mock_rpc + + request = {} + await client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_playbook_async( + transport: str = "grpc_asyncio", request_type=gcdc_playbook.CreatePlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + ) + response = await client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_playbook.CreatePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.asyncio +async def test_create_playbook_async_from_dict(): + await test_create_playbook_async(request_type=dict) + + +def test_create_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_playbook.CreatePlaybookRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + call.return_value = gcdc_playbook.Playbook() + client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_playbook.CreatePlaybookRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook() + ) + await client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_playbook_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_playbook( + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].playbook + mock_val = gcdc_playbook.Playbook(name="name_value") + assert arg == mock_val + + +def test_create_playbook_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook( + gcdc_playbook.CreatePlaybookRequest(), + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_playbook_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_playbook( + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].playbook + mock_val = gcdc_playbook.Playbook(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_playbook_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_playbook( + gcdc_playbook.CreatePlaybookRequest(), + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.DeletePlaybookRequest, + dict, + ], +) +def test_delete_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.DeletePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.DeletePlaybookRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.DeletePlaybookRequest( + name="name_value", + ) + + +def test_delete_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_playbook] = mock_rpc + request = {} + client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_playbook + ] = mock_rpc + + request = {} + await client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_playbook_async( + transport: str = "grpc_asyncio", request_type=playbook.DeletePlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.DeletePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_playbook_async_from_dict(): + await test_delete_playbook_async(request_type=dict) + + +def test_delete_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.DeletePlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + call.return_value = None + client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.DeletePlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_playbook_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__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_playbook( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_playbook_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook( + playbook.DeletePlaybookRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_playbook_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__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_playbook( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_playbook_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_playbook( + playbook.DeletePlaybookRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ListPlaybooksRequest, + dict, + ], +) +def test_list_playbooks(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybooksResponse( + next_page_token="next_page_token_value", + ) + response = client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.ListPlaybooksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybooksPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_playbooks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.ListPlaybooksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_playbooks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.ListPlaybooksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_playbooks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_playbooks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_playbooks] = mock_rpc + request = {} + client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_playbooks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_playbooks_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_playbooks + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_playbooks + ] = mock_rpc + + request = {} + await client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_playbooks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_playbooks_async( + transport: str = "grpc_asyncio", request_type=playbook.ListPlaybooksRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybooksResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.ListPlaybooksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybooksAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_playbooks_async_from_dict(): + await test_list_playbooks_async(request_type=dict) + + +def test_list_playbooks_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ListPlaybooksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + call.return_value = playbook.ListPlaybooksResponse() + client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbooks_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ListPlaybooksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybooksResponse() + ) + await client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_playbooks_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybooksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_playbooks( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_playbooks_flattened_error(): + client = PlaybooksClient( + credentials=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_playbooks( + playbook.ListPlaybooksRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_playbooks_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybooksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybooksResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_playbooks( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_playbooks_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_playbooks( + playbook.ListPlaybooksRequest(), + parent="parent_value", + ) + + +def test_list_playbooks_pager(transport_name: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + playbook.Playbook(), + ], + next_page_token="abc", + ), + playbook.ListPlaybooksResponse( + playbooks=[], + next_page_token="def", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_playbooks(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, playbook.Playbook) for i in results) + + +def test_list_playbooks_pages(transport_name: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + playbook.Playbook(), + ], + next_page_token="abc", + ), + playbook.ListPlaybooksResponse( + playbooks=[], + next_page_token="def", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + ], + ), + RuntimeError, + ) + pages = list(client.list_playbooks(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_playbooks_async_pager(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbooks), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + playbook.Playbook(), + ], + next_page_token="abc", + ), + playbook.ListPlaybooksResponse( + playbooks=[], + next_page_token="def", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_playbooks( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, playbook.Playbook) for i in responses) + + +@pytest.mark.asyncio +async def test_list_playbooks_async_pages(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbooks), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + playbook.Playbook(), + ], + next_page_token="abc", + ), + playbook.ListPlaybooksResponse( + playbooks=[], + next_page_token="def", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_playbooks(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.GetPlaybookRequest, + dict, + ], +) +def test_get_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=playbook.Playbook.PlaybookType.TASK, + ) + response = client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.GetPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == playbook.Playbook.PlaybookType.TASK + + +def test_get_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.GetPlaybookRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.GetPlaybookRequest( + name="name_value", + ) + + +def test_get_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_playbook] = mock_rpc + request = {} + client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_playbook + ] = mock_rpc + + request = {} + await client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_playbook_async( + transport: str = "grpc_asyncio", request_type=playbook.GetPlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=playbook.Playbook.PlaybookType.TASK, + ) + ) + response = await client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.GetPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.asyncio +async def test_get_playbook_async_from_dict(): + await test_get_playbook_async(request_type=dict) + + +def test_get_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.GetPlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + call.return_value = playbook.Playbook() + client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.GetPlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(playbook.Playbook()) + await client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_playbook_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.Playbook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_playbook( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_playbook_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook( + playbook.GetPlaybookRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_playbook_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.Playbook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(playbook.Playbook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_playbook( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_playbook_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_playbook( + playbook.GetPlaybookRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ExportPlaybookRequest, + dict, + ], +) +def test_export_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.ExportPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.ExportPlaybookRequest( + name="name_value", + playbook_uri="playbook_uri_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.export_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.ExportPlaybookRequest( + name="name_value", + playbook_uri="playbook_uri_value", + ) + + +def test_export_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.export_playbook] = mock_rpc + request = {} + client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_export_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.export_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.export_playbook + ] = mock_rpc + + request = {} + await client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.export_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_export_playbook_async( + transport: str = "grpc_asyncio", request_type=playbook.ExportPlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__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_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.ExportPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_playbook_async_from_dict(): + await test_export_playbook_async(request_type=dict) + + +def test_export_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ExportPlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ExportPlaybookRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ImportPlaybookRequest, + dict, + ], +) +def test_import_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.ImportPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.ImportPlaybookRequest( + parent="parent_value", + playbook_uri="playbook_uri_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.ImportPlaybookRequest( + parent="parent_value", + playbook_uri="playbook_uri_value", + ) + + +def test_import_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_playbook] = mock_rpc + request = {} + client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.import_playbook + ] = mock_rpc + + request = {} + await client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_playbook_async( + transport: str = "grpc_asyncio", request_type=playbook.ImportPlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__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_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.ImportPlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_playbook_async_from_dict(): + await test_import_playbook_async(request_type=dict) + + +def test_import_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ImportPlaybookRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ImportPlaybookRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_playbook.UpdatePlaybookRequest, + dict, + ], +) +def test_update_playbook(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + response = client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_playbook.UpdatePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +def test_update_playbook_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_playbook.UpdatePlaybookRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_playbook(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_playbook.UpdatePlaybookRequest() + + +def test_update_playbook_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_playbook] = mock_rpc + request = {} + client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_playbook_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_playbook + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_playbook + ] = mock_rpc + + request = {} + await client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_playbook_async( + transport: str = "grpc_asyncio", request_type=gcdc_playbook.UpdatePlaybookRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + ) + response = await client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_playbook.UpdatePlaybookRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.asyncio +async def test_update_playbook_async_from_dict(): + await test_update_playbook_async(request_type=dict) + + +def test_update_playbook_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_playbook.UpdatePlaybookRequest() + + request.playbook.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + call.return_value = gcdc_playbook.Playbook() + client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "playbook.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_playbook_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_playbook.UpdatePlaybookRequest() + + request.playbook.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook() + ) + await client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "playbook.name=name_value", + ) in kw["metadata"] + + +def test_update_playbook_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_playbook( + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].playbook + mock_val = gcdc_playbook.Playbook(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_playbook_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook( + gcdc_playbook.UpdatePlaybookRequest(), + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_playbook_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_playbook.Playbook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_playbook( + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].playbook + mock_val = gcdc_playbook.Playbook(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_playbook_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_playbook( + gcdc_playbook.UpdatePlaybookRequest(), + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.CreatePlaybookVersionRequest, + dict, + ], +) +def test_create_playbook_version(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + response = client.create_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.CreatePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_create_playbook_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_playbook_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.CreatePlaybookVersionRequest( + parent="parent_value", + ) + + +def test_create_playbook_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_playbook_version + ] = mock_rpc + request = {} + client.create_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_playbook_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_playbook_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_playbook_version + ] = mock_rpc + + request = {} + await client.create_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_playbook_version_async( + transport: str = "grpc_asyncio", request_type=playbook.CreatePlaybookVersionRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + ) + response = await client.create_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.CreatePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_create_playbook_version_async_from_dict(): + await test_create_playbook_version_async(request_type=dict) + + +def test_create_playbook_version_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.CreatePlaybookVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + call.return_value = playbook.PlaybookVersion() + client.create_playbook_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_playbook_version_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.CreatePlaybookVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion() + ) + await client.create_playbook_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_playbook_version_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_playbook_version( + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].playbook_version + mock_val = playbook.PlaybookVersion(name="name_value") + assert arg == mock_val + + +def test_create_playbook_version_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook_version( + playbook.CreatePlaybookVersionRequest(), + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_playbook_version_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_playbook_version( + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].playbook_version + mock_val = playbook.PlaybookVersion(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_playbook_version_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_playbook_version( + playbook.CreatePlaybookVersionRequest(), + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.GetPlaybookVersionRequest, + dict, + ], +) +def test_get_playbook_version(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + response = client.get_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.GetPlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_playbook_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.GetPlaybookVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_playbook_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.GetPlaybookVersionRequest( + name="name_value", + ) + + +def test_get_playbook_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_playbook_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_playbook_version + ] = mock_rpc + request = {} + client.get_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_playbook_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_playbook_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_playbook_version + ] = mock_rpc + + request = {} + await client.get_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_playbook_version_async( + transport: str = "grpc_asyncio", request_type=playbook.GetPlaybookVersionRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + ) + response = await client.get_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.GetPlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_get_playbook_version_async_from_dict(): + await test_get_playbook_version_async(request_type=dict) + + +def test_get_playbook_version_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.GetPlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + call.return_value = playbook.PlaybookVersion() + client.get_playbook_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_playbook_version_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.GetPlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion() + ) + await client.get_playbook_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_playbook_version_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_playbook_version_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook_version( + playbook.GetPlaybookVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_playbook_version_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.PlaybookVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_playbook_version_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_playbook_version( + playbook.GetPlaybookVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.RestorePlaybookVersionRequest, + dict, + ], +) +def test_restore_playbook_version(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.RestorePlaybookVersionResponse() + response = client.restore_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.RestorePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.RestorePlaybookVersionResponse) + + +def test_restore_playbook_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.RestorePlaybookVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.restore_playbook_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.RestorePlaybookVersionRequest( + name="name_value", + ) + + +def test_restore_playbook_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restore_playbook_version + ] = mock_rpc + request = {} + client.restore_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_playbook_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.restore_playbook_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.restore_playbook_version + ] = mock_rpc + + request = {} + await client.restore_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.restore_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_playbook_version_async( + transport: str = "grpc_asyncio", request_type=playbook.RestorePlaybookVersionRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.RestorePlaybookVersionResponse() + ) + response = await client.restore_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.RestorePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.RestorePlaybookVersionResponse) + + +@pytest.mark.asyncio +async def test_restore_playbook_version_async_from_dict(): + await test_restore_playbook_version_async(request_type=dict) + + +def test_restore_playbook_version_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.RestorePlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + call.return_value = playbook.RestorePlaybookVersionResponse() + client.restore_playbook_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_restore_playbook_version_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.RestorePlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.RestorePlaybookVersionResponse() + ) + await client.restore_playbook_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_restore_playbook_version_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.RestorePlaybookVersionResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_restore_playbook_version_flattened_error(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_playbook_version( + playbook.RestorePlaybookVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_restore_playbook_version_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.RestorePlaybookVersionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.RestorePlaybookVersionResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_restore_playbook_version_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_playbook_version( + playbook.RestorePlaybookVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ListPlaybookVersionsRequest, + dict, + ], +) +def test_list_playbook_versions(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybookVersionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_playbook_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.ListPlaybookVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybookVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_playbook_versions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.ListPlaybookVersionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_playbook_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.ListPlaybookVersionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_playbook_versions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_playbook_versions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_playbook_versions + ] = mock_rpc + request = {} + client.list_playbook_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_playbook_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_playbook_versions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_playbook_versions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_playbook_versions + ] = mock_rpc + + request = {} + await client.list_playbook_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_playbook_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_playbook_versions_async( + transport: str = "grpc_asyncio", request_type=playbook.ListPlaybookVersionsRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybookVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_playbook_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.ListPlaybookVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybookVersionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_playbook_versions_async_from_dict(): + await test_list_playbook_versions_async(request_type=dict) + + +def test_list_playbook_versions_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ListPlaybookVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + call.return_value = playbook.ListPlaybookVersionsResponse() + client.list_playbook_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_playbook_versions_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.ListPlaybookVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybookVersionsResponse() + ) + await client.list_playbook_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_playbook_versions_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybookVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_playbook_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_playbook_versions_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook_versions( + playbook.ListPlaybookVersionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_playbook_versions_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = playbook.ListPlaybookVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybookVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_playbook_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_playbook_versions_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_playbook_versions( + playbook.ListPlaybookVersionsRequest(), + parent="parent_value", + ) + + +def test_list_playbook_versions_pager(transport_name: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + next_page_token="abc", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[], + next_page_token="def", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_playbook_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, playbook.PlaybookVersion) for i in results) + + +def test_list_playbook_versions_pages(transport_name: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + next_page_token="abc", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[], + next_page_token="def", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_playbook_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_playbook_versions_async_pager(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + next_page_token="abc", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[], + next_page_token="def", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_playbook_versions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, playbook.PlaybookVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_playbook_versions_async_pages(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + next_page_token="abc", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[], + next_page_token="def", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_playbook_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.DeletePlaybookVersionRequest, + dict, + ], +) +def test_delete_playbook_version(request_type, transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = playbook.DeletePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_playbook_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = playbook.DeletePlaybookVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_playbook_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == playbook.DeletePlaybookVersionRequest( + name="name_value", + ) + + +def test_delete_playbook_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_playbook_version + ] = mock_rpc + request = {} + client.delete_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_playbook_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_playbook_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_playbook_version + ] = mock_rpc + + request = {} + await client.delete_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_playbook_version_async( + transport: str = "grpc_asyncio", request_type=playbook.DeletePlaybookVersionRequest +): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = playbook.DeletePlaybookVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_playbook_version_async_from_dict(): + await test_delete_playbook_version_async(request_type=dict) + + +def test_delete_playbook_version_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.DeletePlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + call.return_value = None + client.delete_playbook_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_playbook_version_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = playbook.DeletePlaybookVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_playbook_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_playbook_version_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_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_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_playbook_version_flattened_error(): + client = PlaybooksClient( + credentials=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_playbook_version( + playbook.DeletePlaybookVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_playbook_version_flattened_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_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_playbook_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_playbook_version_flattened_error_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_playbook_version( + playbook.DeletePlaybookVersionRequest(), + name="name_value", + ) + + +def test_create_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_playbook] = mock_rpc + + request = {} + client.create_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_playbook_rest_required_fields( + request_type=gcdc_playbook.CreatePlaybookRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_playbook._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "playbook", + ) + ) + ) + + +def test_create_playbook_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_playbook(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*}/playbooks" + % client.transport._host, + args[1], + ) + + +def test_create_playbook_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_playbook( + gcdc_playbook.CreatePlaybookRequest(), + parent="parent_value", + playbook=gcdc_playbook.Playbook(name="name_value"), + ) + + +def test_delete_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_playbook] = mock_rpc + + request = {} + client.delete_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_playbook_rest_required_fields( + request_type=playbook.DeletePlaybookRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_playbook._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_playbook_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_playbook(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_playbook_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_playbook( + playbook.DeletePlaybookRequest(), + name="name_value", + ) + + +def test_list_playbooks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_playbooks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_playbooks] = mock_rpc + + request = {} + client.list_playbooks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_playbooks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_playbooks_rest_required_fields( + request_type=playbook.ListPlaybooksRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_playbooks._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_playbooks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybooksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.ListPlaybooksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_playbooks(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_playbooks_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_playbooks._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_playbooks_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybooksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.ListPlaybooksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_playbooks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*}/playbooks" + % client.transport._host, + args[1], + ) + + +def test_list_playbooks_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_playbooks( + playbook.ListPlaybooksRequest(), + parent="parent_value", + ) + + +def test_list_playbooks_rest_pager(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + playbook.Playbook(), + ], + next_page_token="abc", + ), + playbook.ListPlaybooksResponse( + playbooks=[], + next_page_token="def", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybooksResponse( + playbooks=[ + playbook.Playbook(), + playbook.Playbook(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(playbook.ListPlaybooksResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + pager = client.list_playbooks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, playbook.Playbook) for i in results) + + pages = list(client.list_playbooks(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_playbook] = mock_rpc + + request = {} + client.get_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_playbook_rest_required_fields(request_type=playbook.GetPlaybookRequest): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.Playbook() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_playbook._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_playbook_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.Playbook() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_playbook(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*}" + % client.transport._host, + args[1], + ) + + +def test_get_playbook_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_playbook( + playbook.GetPlaybookRequest(), + name="name_value", + ) + + +def test_export_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.export_playbook] = mock_rpc + + request = {} + client.export_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_export_playbook_rest_required_fields( + request_type=playbook.ExportPlaybookRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_export_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_playbook._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_import_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_playbook] = mock_rpc + + request = {} + client.import_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_playbook_rest_required_fields( + request_type=playbook.ImportPlaybookRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_playbook._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_update_playbook_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_playbook in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_playbook] = mock_rpc + + request = {} + client.update_playbook(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_playbook(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_playbook_rest_required_fields( + request_type=gcdc_playbook.UpdatePlaybookRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_playbook._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_playbook._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_playbook(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_playbook_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_playbook._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("playbook",))) + + +def test_update_playbook_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook() + + # get arguments that satisfy an http rule for this method + sample_request = { + "playbook": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_playbook(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{playbook.name=projects/*/locations/*/agents/*/playbooks/*}" + % client.transport._host, + args[1], + ) + + +def test_update_playbook_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_playbook( + gcdc_playbook.UpdatePlaybookRequest(), + playbook=gcdc_playbook.Playbook(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_create_playbook_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_playbook_version + ] = mock_rpc + + request = {} + client.create_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_playbook_version_rest_required_fields( + request_type=playbook.CreatePlaybookVersionRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_playbook_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_playbook_version_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_playbook_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "playbookVersion", + ) + ) + ) + + +def test_create_playbook_version_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_playbook_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_create_playbook_version_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_playbook_version( + playbook.CreatePlaybookVersionRequest(), + parent="parent_value", + playbook_version=playbook.PlaybookVersion(name="name_value"), + ) + + +def test_get_playbook_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_playbook_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_playbook_version + ] = mock_rpc + + request = {} + client.get_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_playbook_version_rest_required_fields( + request_type=playbook.GetPlaybookVersionRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_playbook_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_playbook_version_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_playbook_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_playbook_version_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_playbook_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_playbook_version_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_playbook_version( + playbook.GetPlaybookVersionRequest(), + name="name_value", + ) + + +def test_restore_playbook_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restore_playbook_version + ] = mock_rpc + + request = {} + client.restore_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_playbook_version_rest_required_fields( + request_type=playbook.RestorePlaybookVersionRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.RestorePlaybookVersionResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.RestorePlaybookVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.restore_playbook_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_playbook_version_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_playbook_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_restore_playbook_version_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.RestorePlaybookVersionResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.RestorePlaybookVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.restore_playbook_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_playbook_version_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_playbook_version( + playbook.RestorePlaybookVersionRequest(), + name="name_value", + ) + + +def test_list_playbook_versions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_playbook_versions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_playbook_versions + ] = mock_rpc + + request = {} + client.list_playbook_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_playbook_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_playbook_versions_rest_required_fields( + request_type=playbook.ListPlaybookVersionsRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_playbook_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_playbook_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybookVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.ListPlaybookVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_playbook_versions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_playbook_versions_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_playbook_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_playbook_versions_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybookVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = playbook.ListPlaybookVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_playbook_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/playbooks/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_list_playbook_versions_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_playbook_versions( + playbook.ListPlaybookVersionsRequest(), + parent="parent_value", + ) + + +def test_list_playbook_versions_rest_pager(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + next_page_token="abc", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[], + next_page_token="def", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + ], + next_page_token="ghi", + ), + playbook.ListPlaybookVersionsResponse( + playbook_versions=[ + playbook.PlaybookVersion(), + playbook.PlaybookVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + playbook.ListPlaybookVersionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + + pager = client.list_playbook_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, playbook.PlaybookVersion) for i in results) + + pages = list(client.list_playbook_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_playbook_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_playbook_version + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_playbook_version + ] = mock_rpc + + request = {} + client.delete_playbook_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_playbook_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_playbook_version_rest_required_fields( + request_type=playbook.DeletePlaybookVersionRequest, +): + transport_class = transports.PlaybooksRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_playbook_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_playbook_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_playbook_version_rest_unset_required_fields(): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_playbook_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_playbook_version_rest_flattened(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_playbook_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/playbooks/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_playbook_version_rest_flattened_error(transport: str = "rest"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_playbook_version( + playbook.DeletePlaybookVersionRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlaybooksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PlaybooksClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PlaybooksClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PlaybooksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PlaybooksClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PlaybooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PlaybooksGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PlaybooksGrpcTransport, + transports.PlaybooksGrpcAsyncIOTransport, + transports.PlaybooksRestTransport, + ], +) +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_kind_grpc(): + transport = PlaybooksClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + call.return_value = gcdc_playbook.Playbook() + client.create_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.CreatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + call.return_value = None + client.delete_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_playbooks_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + call.return_value = playbook.ListPlaybooksResponse() + client.list_playbooks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybooksRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + call.return_value = playbook.Playbook() + client.get_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ExportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ImportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_playbook_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + call.return_value = gcdc_playbook.Playbook() + client.update_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.UpdatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_playbook_version_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + call.return_value = playbook.PlaybookVersion() + client.create_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.CreatePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_playbook_version_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + call.return_value = playbook.PlaybookVersion() + client.get_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_playbook_version_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + call.return_value = playbook.RestorePlaybookVersionResponse() + client.restore_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.RestorePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_playbook_versions_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + call.return_value = playbook.ListPlaybookVersionsResponse() + client.list_playbook_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybookVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_playbook_version_empty_call_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + call.return_value = None + client.delete_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookVersionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PlaybooksAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + ) + await client.create_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.CreatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_playbooks_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybooksResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_playbooks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybooksRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=playbook.Playbook.PlaybookType.TASK, + ) + ) + await client.get_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ExportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ImportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_playbook_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + ) + await client.update_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.UpdatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_playbook_version_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + ) + await client.create_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.CreatePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_playbook_version_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + ) + await client.get_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_playbook_version_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.RestorePlaybookVersionResponse() + ) + await client.restore_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.RestorePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_playbook_versions_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + playbook.ListPlaybookVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_playbook_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybookVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_playbook_version_empty_call_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookVersionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PlaybooksClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_playbook_rest_bad_request( + request_type=gcdc_playbook.CreatePlaybookRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_playbook.CreatePlaybookRequest, + dict, + ], +) +def test_create_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request_init["playbook"] = { + "name": "name_value", + "display_name": "display_name_value", + "goal": "goal_value", + "input_parameter_definitions": [ + { + "name": "name_value", + "type_": 1, + "type_schema": { + "inline_schema": {"type_": 1, "items": {}}, + "schema_reference": { + "tool": "tool_value", + "schema": "schema_value", + }, + }, + "description": "description_value", + } + ], + "output_parameter_definitions": {}, + "instruction": { + "guidelines": "guidelines_value", + "steps": [{"text": "text_value", "steps": {}}], + }, + "token_count": 1193, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "referenced_playbooks": [ + "referenced_playbooks_value1", + "referenced_playbooks_value2", + ], + "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"], + "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"], + "inline_actions": ["inline_actions_value1", "inline_actions_value2"], + "code_block": {"code": "code_value"}, + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, + "handlers": [ + { + "event_handler": { + "event": "event_value", + "condition": "condition_value", + "fulfillment": { + "messages": [ + { + "text": { + "text": ["text_value1", "text_value2"], + "allow_playback_interruption": True, + }, + "payload": {"fields": {}}, + "conversation_success": {"metadata": {}}, + "output_audio_text": { + "text": "text_value", + "ssml": "ssml_value", + "allow_playback_interruption": True, + }, + "live_agent_handoff": {"metadata": {}}, + "end_interaction": {}, + "play_audio": { + "audio_uri": "audio_uri_value", + "allow_playback_interruption": True, + }, + "mixed_audio": { + "segments": [ + { + "audio": b"audio_blob", + "uri": "uri_value", + "allow_playback_interruption": True, + } + ] + }, + "telephony_transfer_call": { + "phone_number": "phone_number_value" + }, + "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, + "response_type": 1, + "channel": "channel_value", + } + ], + "webhook": "webhook_value", + "return_partial_responses": True, + "tag": "tag_value", + "set_parameter_actions": [ + { + "parameter": "parameter_value", + "value": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {}, + "list_value": {"values": {}}, + }, + } + ], + "conditional_cases": [ + { + "cases": [ + { + "condition": "condition_value", + "case_content": [ + {"message": {}, "additional_cases": {}} + ], + } + ] + } + ], + "advanced_settings": { + "audio_export_gcs_destination": {"uri": "uri_value"}, + "speech_settings": { + "endpointer_sensitivity": 2402, + "no_speech_timeout": {"seconds": 751, "nanos": 543}, + "use_timeout_based_endpointing": True, + "models": {}, + }, + "dtmf_settings": { + "enabled": True, + "max_digits": 1065, + "finish_digit": "finish_digit_value", + "interdigit_timeout_duration": {}, + "endpointing_timeout_duration": {}, + }, + "logging_settings": { + "enable_stackdriver_logging": True, + "enable_interaction_logging": True, + "enable_consent_based_redaction": True, + }, + }, + "enable_generative_fallback": True, + "generators": [ + { + "generator": "generator_value", + "input_parameters": {}, + "output_parameter": "output_parameter_value", + } + ], + }, + }, + "lifecycle_handler": { + "lifecycle_stage": "lifecycle_stage_value", + "condition": "condition_value", + "fulfillment": {}, + }, + } + ], + "playbook_type": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_playbook.CreatePlaybookRequest.meta.fields["playbook"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["playbook"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["playbook"][field])): + del request_init["playbook"][field][i][subfield] + else: + del request_init["playbook"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_playbook(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_create_playbook" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_create_playbook_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_create_playbook" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_playbook.CreatePlaybookRequest.pb( + gcdc_playbook.CreatePlaybookRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_playbook.Playbook.to_json(gcdc_playbook.Playbook()) + req.return_value.content = return_value + + request = gcdc_playbook.CreatePlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_playbook.Playbook() + post_with_metadata.return_value = gcdc_playbook.Playbook(), metadata + + client.create_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_playbook_rest_bad_request(request_type=playbook.DeletePlaybookRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.DeletePlaybookRequest, + dict, + ], +) +def test_delete_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_playbook(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_delete_playbook" + ) as pre: + pre.assert_not_called() + pb_message = playbook.DeletePlaybookRequest.pb(playbook.DeletePlaybookRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = playbook.DeletePlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_playbooks_rest_bad_request(request_type=playbook.ListPlaybooksRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_playbooks(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ListPlaybooksRequest, + dict, + ], +) +def test_list_playbooks_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybooksResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.ListPlaybooksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_playbooks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybooksPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_playbooks_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_list_playbooks" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_list_playbooks_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_list_playbooks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.ListPlaybooksRequest.pb(playbook.ListPlaybooksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.ListPlaybooksResponse.to_json( + playbook.ListPlaybooksResponse() + ) + req.return_value.content = return_value + + request = playbook.ListPlaybooksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.ListPlaybooksResponse() + post_with_metadata.return_value = playbook.ListPlaybooksResponse(), metadata + + client.list_playbooks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_playbook_rest_bad_request(request_type=playbook.GetPlaybookRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.GetPlaybookRequest, + dict, + ], +) +def test_get_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=playbook.Playbook.PlaybookType.TASK, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_playbook(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_get_playbook" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_get_playbook_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_get_playbook" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.GetPlaybookRequest.pb(playbook.GetPlaybookRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.Playbook.to_json(playbook.Playbook()) + req.return_value.content = return_value + + request = playbook.GetPlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.Playbook() + post_with_metadata.return_value = playbook.Playbook(), metadata + + client.get_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_playbook_rest_bad_request(request_type=playbook.ExportPlaybookRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.export_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ExportPlaybookRequest, + dict, + ], +) +def test_export_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_playbook(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PlaybooksRestInterceptor, "post_export_playbook" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_export_playbook_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_export_playbook" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.ExportPlaybookRequest.pb(playbook.ExportPlaybookRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = playbook.ExportPlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.export_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_import_playbook_rest_bad_request(request_type=playbook.ImportPlaybookRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.import_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ImportPlaybookRequest, + dict, + ], +) +def test_import_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_playbook(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PlaybooksRestInterceptor, "post_import_playbook" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_import_playbook_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_import_playbook" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.ImportPlaybookRequest.pb(playbook.ImportPlaybookRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = playbook.ImportPlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.import_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_playbook_rest_bad_request( + request_type=gcdc_playbook.UpdatePlaybookRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "playbook": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_playbook(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_playbook.UpdatePlaybookRequest, + dict, + ], +) +def test_update_playbook_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "playbook": { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + } + request_init["playbook"] = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4", + "display_name": "display_name_value", + "goal": "goal_value", + "input_parameter_definitions": [ + { + "name": "name_value", + "type_": 1, + "type_schema": { + "inline_schema": {"type_": 1, "items": {}}, + "schema_reference": { + "tool": "tool_value", + "schema": "schema_value", + }, + }, + "description": "description_value", + } + ], + "output_parameter_definitions": {}, + "instruction": { + "guidelines": "guidelines_value", + "steps": [{"text": "text_value", "steps": {}}], + }, + "token_count": 1193, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "referenced_playbooks": [ + "referenced_playbooks_value1", + "referenced_playbooks_value2", + ], + "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"], + "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"], + "inline_actions": ["inline_actions_value1", "inline_actions_value2"], + "code_block": {"code": "code_value"}, + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, + "handlers": [ + { + "event_handler": { + "event": "event_value", + "condition": "condition_value", + "fulfillment": { + "messages": [ + { + "text": { + "text": ["text_value1", "text_value2"], + "allow_playback_interruption": True, + }, + "payload": {"fields": {}}, + "conversation_success": {"metadata": {}}, + "output_audio_text": { + "text": "text_value", + "ssml": "ssml_value", + "allow_playback_interruption": True, + }, + "live_agent_handoff": {"metadata": {}}, + "end_interaction": {}, + "play_audio": { + "audio_uri": "audio_uri_value", + "allow_playback_interruption": True, + }, + "mixed_audio": { + "segments": [ + { + "audio": b"audio_blob", + "uri": "uri_value", + "allow_playback_interruption": True, + } + ] + }, + "telephony_transfer_call": { + "phone_number": "phone_number_value" + }, + "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, + "response_type": 1, + "channel": "channel_value", + } + ], + "webhook": "webhook_value", + "return_partial_responses": True, + "tag": "tag_value", + "set_parameter_actions": [ + { + "parameter": "parameter_value", + "value": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {}, + "list_value": {"values": {}}, + }, + } + ], + "conditional_cases": [ + { + "cases": [ + { + "condition": "condition_value", + "case_content": [ + {"message": {}, "additional_cases": {}} + ], + } + ] + } + ], + "advanced_settings": { + "audio_export_gcs_destination": {"uri": "uri_value"}, + "speech_settings": { + "endpointer_sensitivity": 2402, + "no_speech_timeout": {"seconds": 751, "nanos": 543}, + "use_timeout_based_endpointing": True, + "models": {}, + }, + "dtmf_settings": { + "enabled": True, + "max_digits": 1065, + "finish_digit": "finish_digit_value", + "interdigit_timeout_duration": {}, + "endpointing_timeout_duration": {}, + }, + "logging_settings": { + "enable_stackdriver_logging": True, + "enable_interaction_logging": True, + "enable_consent_based_redaction": True, + }, + }, + "enable_generative_fallback": True, + "generators": [ + { + "generator": "generator_value", + "input_parameters": {}, + "output_parameter": "output_parameter_value", + } + ], + }, + }, + "lifecycle_handler": { + "lifecycle_stage": "lifecycle_stage_value", + "condition": "condition_value", + "fulfillment": {}, + }, + } + ], + "playbook_type": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_playbook.UpdatePlaybookRequest.meta.fields["playbook"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["playbook"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["playbook"][field])): + del request_init["playbook"][field][i][subfield] + else: + del request_init["playbook"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_playbook.Playbook( + name="name_value", + display_name="display_name_value", + goal="goal_value", + token_count=1193, + referenced_playbooks=["referenced_playbooks_value"], + referenced_flows=["referenced_flows_value"], + referenced_tools=["referenced_tools_value"], + inline_actions=["inline_actions_value"], + playbook_type=gcdc_playbook.Playbook.PlaybookType.TASK, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_playbook.Playbook.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_playbook(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_playbook.Playbook) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.goal == "goal_value" + assert response.token_count == 1193 + assert response.referenced_playbooks == ["referenced_playbooks_value"] + assert response.referenced_flows == ["referenced_flows_value"] + assert response.referenced_tools == ["referenced_tools_value"] + assert response.inline_actions == ["inline_actions_value"] + assert response.playbook_type == gcdc_playbook.Playbook.PlaybookType.TASK + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_playbook_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_update_playbook" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_update_playbook_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_update_playbook" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_playbook.UpdatePlaybookRequest.pb( + gcdc_playbook.UpdatePlaybookRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_playbook.Playbook.to_json(gcdc_playbook.Playbook()) + req.return_value.content = return_value + + request = gcdc_playbook.UpdatePlaybookRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_playbook.Playbook() + post_with_metadata.return_value = gcdc_playbook.Playbook(), metadata + + client.update_playbook( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_playbook_version_rest_bad_request( + request_type=playbook.CreatePlaybookVersionRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_playbook_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.CreatePlaybookVersionRequest, + dict, + ], +) +def test_create_playbook_version_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request_init["playbook_version"] = { + "name": "name_value", + "description": "description_value", + "playbook": { + "name": "name_value", + "display_name": "display_name_value", + "goal": "goal_value", + "input_parameter_definitions": [ + { + "name": "name_value", + "type_": 1, + "type_schema": { + "inline_schema": {"type_": 1, "items": {}}, + "schema_reference": { + "tool": "tool_value", + "schema": "schema_value", + }, + }, + "description": "description_value", + } + ], + "output_parameter_definitions": {}, + "instruction": { + "guidelines": "guidelines_value", + "steps": [{"text": "text_value", "steps": {}}], + }, + "token_count": 1193, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "referenced_playbooks": [ + "referenced_playbooks_value1", + "referenced_playbooks_value2", + ], + "referenced_flows": ["referenced_flows_value1", "referenced_flows_value2"], + "referenced_tools": ["referenced_tools_value1", "referenced_tools_value2"], + "inline_actions": ["inline_actions_value1", "inline_actions_value2"], + "code_block": {"code": "code_value"}, + "llm_model_settings": { + "model": "model_value", + "prompt_text": "prompt_text_value", + }, + "handlers": [ + { + "event_handler": { + "event": "event_value", + "condition": "condition_value", + "fulfillment": { + "messages": [ + { + "text": { + "text": ["text_value1", "text_value2"], + "allow_playback_interruption": True, + }, + "payload": {"fields": {}}, + "conversation_success": {"metadata": {}}, + "output_audio_text": { + "text": "text_value", + "ssml": "ssml_value", + "allow_playback_interruption": True, + }, + "live_agent_handoff": {"metadata": {}}, + "end_interaction": {}, + "play_audio": { + "audio_uri": "audio_uri_value", + "allow_playback_interruption": True, + }, + "mixed_audio": { + "segments": [ + { + "audio": b"audio_blob", + "uri": "uri_value", + "allow_playback_interruption": True, + } + ] + }, + "telephony_transfer_call": { + "phone_number": "phone_number_value" + }, + "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, + "response_type": 1, + "channel": "channel_value", + } + ], + "webhook": "webhook_value", + "return_partial_responses": True, + "tag": "tag_value", + "set_parameter_actions": [ + { + "parameter": "parameter_value", + "value": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {}, + "list_value": {"values": {}}, + }, + } + ], + "conditional_cases": [ + { + "cases": [ + { + "condition": "condition_value", + "case_content": [ + {"message": {}, "additional_cases": {}} + ], + } + ] + } + ], + "advanced_settings": { + "audio_export_gcs_destination": {"uri": "uri_value"}, + "speech_settings": { + "endpointer_sensitivity": 2402, + "no_speech_timeout": {"seconds": 751, "nanos": 543}, + "use_timeout_based_endpointing": True, + "models": {}, + }, + "dtmf_settings": { + "enabled": True, + "max_digits": 1065, + "finish_digit": "finish_digit_value", + "interdigit_timeout_duration": {}, + "endpointing_timeout_duration": {}, + }, + "logging_settings": { + "enable_stackdriver_logging": True, + "enable_interaction_logging": True, + "enable_consent_based_redaction": True, + }, + }, + "enable_generative_fallback": True, + "generators": [ + { + "generator": "generator_value", + "input_parameters": {}, + "output_parameter": "output_parameter_value", + } + ], + }, + }, + "lifecycle_handler": { + "lifecycle_stage": "lifecycle_stage_value", + "condition": "condition_value", + "fulfillment": {}, + }, + } + ], + "playbook_type": 1, + }, + "examples": [ + { + "name": "name_value", + "playbook_input": { + "preceding_conversation_summary": "preceding_conversation_summary_value" + }, + "playbook_output": {"execution_summary": "execution_summary_value"}, + "actions": [ + { + "user_utterance": {"text": "text_value"}, + "agent_utterance": {"text": "text_value"}, + "tool_use": { + "tool": "tool_value", + "display_name": "display_name_value", + "action": "action_value", + "input_action_parameters": {}, + "output_action_parameters": {}, + }, + "playbook_invocation": { + "playbook": "playbook_value", + "display_name": "display_name_value", + "playbook_input": {}, + "playbook_output": {}, + "playbook_state": 1, + }, + "flow_invocation": { + "flow": "flow_value", + "display_name": "display_name_value", + "flow_state": 1, + }, + "playbook_transition": { + "playbook": "playbook_value", + "display_name": "display_name_value", + }, + "flow_transition": { + "flow": "flow_value", + "display_name": "display_name_value", + }, + } + ], + "display_name": "display_name_value", + "description": "description_value", + "token_count": 1193, + "create_time": {}, + "update_time": {}, + "conversation_state": 1, + "language_code": "language_code_value", + } + ], + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = playbook.CreatePlaybookVersionRequest.meta.fields["playbook_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["playbook_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["playbook_version"][field])): + del request_init["playbook_version"][field][i][subfield] + else: + del request_init["playbook_version"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_playbook_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_playbook_version_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_create_playbook_version" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, + "post_create_playbook_version_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_create_playbook_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.CreatePlaybookVersionRequest.pb( + playbook.CreatePlaybookVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.PlaybookVersion.to_json(playbook.PlaybookVersion()) + req.return_value.content = return_value + + request = playbook.CreatePlaybookVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.PlaybookVersion() + post_with_metadata.return_value = playbook.PlaybookVersion(), metadata + + client.create_playbook_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_playbook_version_rest_bad_request( + request_type=playbook.GetPlaybookVersionRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_playbook_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.GetPlaybookVersionRequest, + dict, + ], +) +def test_get_playbook_version_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.PlaybookVersion( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.PlaybookVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_playbook_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.PlaybookVersion) + assert response.name == "name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_playbook_version_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_get_playbook_version" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_get_playbook_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_get_playbook_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.GetPlaybookVersionRequest.pb( + playbook.GetPlaybookVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.PlaybookVersion.to_json(playbook.PlaybookVersion()) + req.return_value.content = return_value + + request = playbook.GetPlaybookVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.PlaybookVersion() + post_with_metadata.return_value = playbook.PlaybookVersion(), metadata + + client.get_playbook_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_restore_playbook_version_rest_bad_request( + request_type=playbook.RestorePlaybookVersionRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.restore_playbook_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.RestorePlaybookVersionRequest, + dict, + ], +) +def test_restore_playbook_version_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.RestorePlaybookVersionResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.RestorePlaybookVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.restore_playbook_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, playbook.RestorePlaybookVersionResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_playbook_version_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_restore_playbook_version" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, + "post_restore_playbook_version_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_restore_playbook_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.RestorePlaybookVersionRequest.pb( + playbook.RestorePlaybookVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.RestorePlaybookVersionResponse.to_json( + playbook.RestorePlaybookVersionResponse() + ) + req.return_value.content = return_value + + request = playbook.RestorePlaybookVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.RestorePlaybookVersionResponse() + post_with_metadata.return_value = ( + playbook.RestorePlaybookVersionResponse(), + metadata, + ) + + client.restore_playbook_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_playbook_versions_rest_bad_request( + request_type=playbook.ListPlaybookVersionsRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_playbook_versions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.ListPlaybookVersionsRequest, + dict, + ], +) +def test_list_playbook_versions_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = playbook.ListPlaybookVersionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = playbook.ListPlaybookVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_playbook_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPlaybookVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_playbook_versions_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_list_playbook_versions" + ) as post, mock.patch.object( + transports.PlaybooksRestInterceptor, "post_list_playbook_versions_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_list_playbook_versions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = playbook.ListPlaybookVersionsRequest.pb( + playbook.ListPlaybookVersionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = playbook.ListPlaybookVersionsResponse.to_json( + playbook.ListPlaybookVersionsResponse() + ) + req.return_value.content = return_value + + request = playbook.ListPlaybookVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = playbook.ListPlaybookVersionsResponse() + post_with_metadata.return_value = ( + playbook.ListPlaybookVersionsResponse(), + metadata, + ) + + client.list_playbook_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_playbook_version_rest_bad_request( + request_type=playbook.DeletePlaybookVersionRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_playbook_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + playbook.DeletePlaybookVersionRequest, + dict, + ], +) +def test_delete_playbook_version_rest_call_success(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/playbooks/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_playbook_version(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_playbook_version_rest_interceptors(null_interceptor): + transport = transports.PlaybooksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PlaybooksRestInterceptor(), + ) + client = PlaybooksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PlaybooksRestInterceptor, "pre_delete_playbook_version" + ) as pre: + pre.assert_not_called() + pb_message = playbook.DeletePlaybookVersionRequest.pb( + playbook.DeletePlaybookVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = playbook.DeletePlaybookVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_playbook_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_playbook), "__call__") as call: + client.create_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.CreatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_playbook), "__call__") as call: + client.delete_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_playbooks_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_playbooks), "__call__") as call: + client.list_playbooks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybooksRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_playbook), "__call__") as call: + client.get_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_playbook), "__call__") as call: + client.export_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ExportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_playbook), "__call__") as call: + client.import_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ImportPlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_playbook_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_playbook), "__call__") as call: + client.update_playbook(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_playbook.UpdatePlaybookRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_playbook_version_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_playbook_version), "__call__" + ) as call: + client.create_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.CreatePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_playbook_version_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_playbook_version), "__call__" + ) as call: + client.get_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.GetPlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_playbook_version_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_playbook_version), "__call__" + ) as call: + client.restore_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.RestorePlaybookVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_playbook_versions_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_playbook_versions), "__call__" + ) as call: + client.list_playbook_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.ListPlaybookVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_playbook_version_empty_call_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_playbook_version), "__call__" + ) as call: + client.delete_playbook_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = playbook.DeletePlaybookVersionRequest() + + assert args[0] == request_msg + + +def test_playbooks_rest_lro_client(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PlaybooksGrpcTransport, + ) + + +def test_playbooks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PlaybooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_playbooks_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3.services.playbooks.transports.PlaybooksTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PlaybooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_playbook", + "delete_playbook", + "list_playbooks", + "get_playbook", + "export_playbook", + "import_playbook", + "update_playbook", + "create_playbook_version", + "get_playbook_version", + "restore_playbook_version", + "list_playbook_versions", + "delete_playbook_version", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_playbooks_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.playbooks.transports.PlaybooksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PlaybooksTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_playbooks_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.playbooks.transports.PlaybooksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PlaybooksTransport() + adc.assert_called_once() + + +def test_playbooks_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) + PlaybooksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PlaybooksGrpcTransport, + transports.PlaybooksGrpcAsyncIOTransport, + ], +) +def test_playbooks_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.PlaybooksGrpcTransport, + transports.PlaybooksGrpcAsyncIOTransport, + transports.PlaybooksRestTransport, + ], +) +def test_playbooks_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PlaybooksGrpcTransport, grpc_helpers), + (transports.PlaybooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_playbooks_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.PlaybooksGrpcTransport, transports.PlaybooksGrpcAsyncIOTransport], +) +def test_playbooks_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_playbooks_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.PlaybooksRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_playbooks_host_no_port(transport_name): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_playbooks_host_with_port(transport_name): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_playbooks_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PlaybooksClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PlaybooksClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_playbook._session + session2 = client2.transport.create_playbook._session + assert session1 != session2 + session1 = client1.transport.delete_playbook._session + session2 = client2.transport.delete_playbook._session + assert session1 != session2 + session1 = client1.transport.list_playbooks._session + session2 = client2.transport.list_playbooks._session + assert session1 != session2 + session1 = client1.transport.get_playbook._session + session2 = client2.transport.get_playbook._session + assert session1 != session2 + session1 = client1.transport.export_playbook._session + session2 = client2.transport.export_playbook._session + assert session1 != session2 + session1 = client1.transport.import_playbook._session + session2 = client2.transport.import_playbook._session + assert session1 != session2 + session1 = client1.transport.update_playbook._session + session2 = client2.transport.update_playbook._session + assert session1 != session2 + session1 = client1.transport.create_playbook_version._session + session2 = client2.transport.create_playbook_version._session + assert session1 != session2 + session1 = client1.transport.get_playbook_version._session + session2 = client2.transport.get_playbook_version._session + assert session1 != session2 + session1 = client1.transport.restore_playbook_version._session + session2 = client2.transport.restore_playbook_version._session + assert session1 != session2 + session1 = client1.transport.list_playbook_versions._session + session2 = client2.transport.list_playbook_versions._session + assert session1 != session2 + session1 = client1.transport.delete_playbook_version._session + session2 = client2.transport.delete_playbook_version._session + assert session1 != session2 + + +def test_playbooks_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PlaybooksGrpcTransport( + 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_playbooks_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PlaybooksGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.PlaybooksGrpcTransport, transports.PlaybooksGrpcAsyncIOTransport], +) +def test_playbooks_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.PlaybooksGrpcTransport, transports.PlaybooksGrpcAsyncIOTransport], +) +def test_playbooks_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_playbooks_grpc_lro_client(): + client = PlaybooksClient( + 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_playbooks_grpc_lro_async_client(): + client = PlaybooksAsyncClient( + 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_example_path(): + project = "squid" + location = "clam" + agent = "whelk" + playbook = "octopus" + example = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/examples/{example}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + example=example, + ) + actual = PlaybooksClient.example_path(project, location, agent, playbook, example) + assert expected == actual + + +def test_parse_example_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "playbook": "winkle", + "example": "nautilus", + } + path = PlaybooksClient.example_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_example_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 = PlaybooksClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "flow": "nudibranch", + } + path = PlaybooksClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_flow_path(path) + assert expected == actual + + +def test_generator_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + generator = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/generators/{generator}".format( + project=project, + location=location, + agent=agent, + generator=generator, + ) + actual = PlaybooksClient.generator_path(project, location, agent, generator) + assert expected == actual + + +def test_parse_generator_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "generator": "clam", + } + path = PlaybooksClient.generator_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_generator_path(path) + assert expected == actual + + +def test_playbook_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + playbook = "nudibranch" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + ) + actual = PlaybooksClient.playbook_path(project, location, agent, playbook) + assert expected == actual + + +def test_parse_playbook_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "playbook": "nautilus", + } + path = PlaybooksClient.playbook_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_playbook_path(path) + assert expected == actual + + +def test_playbook_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + playbook = "clam" + version = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}/versions/{version}".format( + project=project, + location=location, + agent=agent, + playbook=playbook, + version=version, + ) + actual = PlaybooksClient.playbook_version_path( + project, location, agent, playbook, version + ) + assert expected == actual + + +def test_parse_playbook_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "playbook": "cuttlefish", + "version": "mussel", + } + path = PlaybooksClient.playbook_version_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_playbook_version_path(path) + assert expected == actual + + +def test_tool_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + tool = "abalone" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = PlaybooksClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "tool": "octopus", + } + path = PlaybooksClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_tool_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 = PlaybooksClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "webhook": "abalone", + } + path = PlaybooksClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.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 = PlaybooksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = PlaybooksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = PlaybooksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = PlaybooksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = PlaybooksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = PlaybooksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = PlaybooksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = PlaybooksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.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 = PlaybooksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = PlaybooksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PlaybooksClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.PlaybooksTransport, "_prep_wrapped_messages" + ) as prep: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.PlaybooksTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PlaybooksClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = PlaybooksClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = PlaybooksAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = PlaybooksAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = PlaybooksClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (PlaybooksClient, transports.PlaybooksGrpcTransport), + (PlaybooksAsyncClient, transports.PlaybooksGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_sessions.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_sessions.py index 93a618316226..2b38a7616390 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_sessions.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_sessions.py @@ -66,10 +66,12 @@ from google.cloud.dialogflowcx_v3.types import ( audio_config, entity_type, + generative_settings, intent, page, session, session_entity_type, + tool_call, ) CRED_INFO_JSON = { @@ -5355,41 +5357,70 @@ def test_parse_page_path(): assert expected == actual -def test_session_path(): +def test_playbook_path(): project = "squid" location = "clam" agent = "whelk" - session = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format( + playbook = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( project=project, location=location, agent=agent, - session=session, + playbook=playbook, ) - actual = SessionsClient.session_path(project, location, agent, session) + actual = SessionsClient.playbook_path(project, location, agent, playbook) assert expected == actual -def test_parse_session_path(): +def test_parse_playbook_path(): expected = { "project": "oyster", "location": "nudibranch", "agent": "cuttlefish", - "session": "mussel", + "playbook": "mussel", } - path = SessionsClient.session_path(**expected) + path = SessionsClient.playbook_path(**expected) # Check that the path construction is reversible. - actual = SessionsClient.parse_session_path(path) + actual = SessionsClient.parse_playbook_path(path) assert expected == actual -def test_session_entity_type_path(): +def test_session_path(): project = "winkle" location = "nautilus" agent = "scallop" session = "abalone" - entity_type = "squid" + 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": "squid", + "location": "clam", + "agent": "whelk", + "session": "octopus", + } + 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 = "oyster" + location = "nudibranch" + agent = "cuttlefish" + session = "mussel" + entity_type = "winkle" expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -5405,11 +5436,11 @@ def test_session_entity_type_path(): def test_parse_session_entity_type_path(): expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "session": "oyster", - "entity_type": "nudibranch", + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "session": "squid", + "entity_type": "clam", } path = SessionsClient.session_entity_type_path(**expected) @@ -5418,12 +5449,43 @@ def test_parse_session_entity_type_path(): assert expected == actual +def test_tool_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + tool = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = SessionsClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "tool": "nautilus", + } + path = SessionsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_tool_path(path) + assert expected == actual + + def test_transition_route_group_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - flow = "nautilus" - transition_route_group = "scallop" + 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, @@ -5439,11 +5501,11 @@ def test_transition_route_group_path(): def test_parse_transition_route_group_path(): expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "flow": "whelk", - "transition_route_group": "octopus", + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", } path = SessionsClient.transition_route_group_path(**expected) @@ -5453,11 +5515,11 @@ def test_parse_transition_route_group_path(): def test_version_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - version = "winkle" + 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, @@ -5471,11 +5533,11 @@ def test_version_path(): def test_parse_version_path(): expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "version": "clam", + "project": "clam", + "location": "whelk", + "agent": "octopus", + "flow": "oyster", + "version": "nudibranch", } path = SessionsClient.version_path(**expected) @@ -5485,10 +5547,10 @@ def test_parse_version_path(): def test_webhook_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - webhook = "nudibranch" + project = "cuttlefish" + location = "mussel" + agent = "winkle" + webhook = "nautilus" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -5501,10 +5563,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "webhook": "nautilus", + "project": "scallop", + "location": "abalone", + "agent": "squid", + "webhook": "clam", } path = SessionsClient.webhook_path(**expected) @@ -5514,7 +5576,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5524,7 +5586,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "octopus", } path = SessionsClient.common_billing_account_path(**expected) @@ -5534,7 +5596,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -5544,7 +5606,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "nudibranch", } path = SessionsClient.common_folder_path(**expected) @@ -5554,7 +5616,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -5564,7 +5626,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "mussel", } path = SessionsClient.common_organization_path(**expected) @@ -5574,7 +5636,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -5584,7 +5646,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "nautilus", } path = SessionsClient.common_project_path(**expected) @@ -5594,8 +5656,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -5606,8 +5668,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "squid", + "location": "clam", } path = SessionsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py index 185cfad7bfbf..8ab82eb08d20 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py @@ -88,6 +88,7 @@ ) from google.cloud.dialogflowcx_v3.types import test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.cloud.dialogflowcx_v3.types import tool_call CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -8621,9 +8622,15 @@ def test_create_test_case_rest_call_success(request_type): "digits": "digits_value", "finish_digit": "finish_digit_value", }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "output_parameters": {"fields": {}}, + }, "language_code": "language_code_value", }, - "injected_parameters": {"fields": {}}, + "injected_parameters": {}, "is_webhook_enabled": True, "enable_sentiment_analysis": True, }, @@ -8696,6 +8703,11 @@ def test_create_test_case_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -8774,6 +8786,7 @@ def test_create_test_case_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], }, @@ -9090,9 +9103,15 @@ def test_update_test_case_rest_call_success(request_type): "digits": "digits_value", "finish_digit": "finish_digit_value", }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "output_parameters": {"fields": {}}, + }, "language_code": "language_code_value", }, - "injected_parameters": {"fields": {}}, + "injected_parameters": {}, "is_webhook_enabled": True, "enable_sentiment_analysis": True, }, @@ -9165,6 +9184,11 @@ def test_update_test_case_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -9243,6 +9267,7 @@ def test_update_test_case_rest_call_success(request_type): "trigger_fulfillment": {}, "target_page": "target_page_value", "target_flow": "target_flow_value", + "target_playbook": "target_playbook_value", } ], }, @@ -11646,41 +11671,70 @@ def test_parse_page_path(): assert expected == actual -def test_test_case_path(): +def test_playbook_path(): project = "winkle" location = "nautilus" agent = "scallop" - test_case = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( + playbook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/playbooks/{playbook}".format( project=project, location=location, agent=agent, - test_case=test_case, + playbook=playbook, ) - actual = TestCasesClient.test_case_path(project, location, agent, test_case) + actual = TestCasesClient.playbook_path(project, location, agent, playbook) assert expected == actual -def test_parse_test_case_path(): +def test_parse_playbook_path(): expected = { "project": "squid", "location": "clam", "agent": "whelk", - "test_case": "octopus", + "playbook": "octopus", } - path = TestCasesClient.test_case_path(**expected) + path = TestCasesClient.playbook_path(**expected) # Check that the path construction is reversible. - actual = TestCasesClient.parse_test_case_path(path) + actual = TestCasesClient.parse_playbook_path(path) assert expected == actual -def test_test_case_result_path(): +def test_test_case_path(): project = "oyster" location = "nudibranch" agent = "cuttlefish" test_case = "mussel" - result = "winkle" + 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": "winkle", + "location": "nautilus", + "agent": "scallop", + "test_case": "abalone", + } + 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 = "squid" + location = "clam" + agent = "whelk" + test_case = "octopus" + result = "oyster" expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -11696,11 +11750,11 @@ def test_test_case_result_path(): def test_parse_test_case_result_path(): expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "test_case": "squid", - "result": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "test_case": "winkle", + "result": "nautilus", } path = TestCasesClient.test_case_result_path(**expected) @@ -11709,12 +11763,43 @@ def test_parse_test_case_result_path(): assert expected == actual +def test_tool_path(): + project = "scallop" + location = "abalone" + agent = "squid" + tool = "clam" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = TestCasesClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "tool": "nudibranch", + } + path = TestCasesClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_tool_path(path) + assert expected == actual + + def test_transition_route_group_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - flow = "nudibranch" - transition_route_group = "cuttlefish" + 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, @@ -11730,11 +11815,11 @@ def test_transition_route_group_path(): def test_parse_transition_route_group_path(): expected = { - "project": "mussel", - "location": "winkle", - "agent": "nautilus", - "flow": "scallop", - "transition_route_group": "abalone", + "project": "abalone", + "location": "squid", + "agent": "clam", + "flow": "whelk", + "transition_route_group": "octopus", } path = TestCasesClient.transition_route_group_path(**expected) @@ -11744,10 +11829,10 @@ def test_parse_transition_route_group_path(): def test_webhook_path(): - project = "squid" - location = "clam" - agent = "whelk" - webhook = "octopus" + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + webhook = "mussel" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -11760,10 +11845,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "webhook": "mussel", + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "webhook": "abalone", } path = TestCasesClient.webhook_path(**expected) @@ -11773,7 +11858,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11783,7 +11868,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "clam", } path = TestCasesClient.common_billing_account_path(**expected) @@ -11793,7 +11878,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -11803,7 +11888,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "octopus", } path = TestCasesClient.common_folder_path(**expected) @@ -11813,7 +11898,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -11823,7 +11908,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nudibranch", } path = TestCasesClient.common_organization_path(**expected) @@ -11833,7 +11918,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -11843,7 +11928,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "mussel", } path = TestCasesClient.common_project_path(**expected) @@ -11853,8 +11938,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11865,8 +11950,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "scallop", + "location": "abalone", } path = TestCasesClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_tools.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_tools.py new file mode 100644 index 000000000000..2961fa3f3246 --- /dev/null +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_tools.py @@ -0,0 +1,11186 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflowcx_v3.services.tools import ( + ToolsAsyncClient, + ToolsClient, + pagers, + transports, +) +from google.cloud.dialogflowcx_v3.types import data_store_connection +from google.cloud.dialogflowcx_v3.types import tool +from google.cloud.dialogflowcx_v3.types import tool as gcdc_tool + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# 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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +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 ToolsClient._get_default_mtls_endpoint(None) is None + assert ToolsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + ToolsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + ) + assert ( + ToolsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ToolsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ToolsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert ToolsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ToolsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ToolsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + ToolsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ToolsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ToolsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ToolsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ToolsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ToolsClient._read_environment_variables() == (False, "auto", "foo.com") + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert ToolsClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ToolsClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert ToolsClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert ToolsClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + ToolsClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert ToolsClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ToolsClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ToolsClient._get_client_cert_source(None, False) is None + assert ToolsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ( + ToolsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ToolsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ToolsClient._get_client_cert_source(mock_provided_cert_source, "true") + is mock_provided_cert_source + ) + + +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ToolsClient._DEFAULT_UNIVERSE + default_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ToolsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ToolsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "always") + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolsClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ToolsClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + ToolsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ToolsClient._get_universe_domain(None, None) == ToolsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ToolsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ToolsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ToolsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ToolsClient, "grpc"), + (ToolsAsyncClient, "grpc_asyncio"), + (ToolsClient, "rest"), + ], +) +def test_tools_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ToolsGrpcTransport, "grpc"), + (transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ToolsRestTransport, "rest"), + ], +) +def test_tools_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ToolsClient, "grpc"), + (ToolsAsyncClient, "grpc_asyncio"), + (ToolsClient, "rest"), + ], +) +def test_tools_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_tools_client_get_transport_class(): + transport = ToolsClient.get_transport_class() + available_transports = [ + transports.ToolsGrpcTransport, + transports.ToolsRestTransport, + ] + assert transport in available_transports + + transport = ToolsClient.get_transport_class("grpc") + assert transport == transports.ToolsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc"), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (ToolsClient, transports.ToolsRestTransport, "rest"), + ], +) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test_tools_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(ToolsClient, "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(ToolsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", "true"), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ToolsClient, transports.ToolsGrpcTransport, "grpc", "false"), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ToolsClient, transports.ToolsRestTransport, "rest", "true"), + (ToolsClient, transports.ToolsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tools_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ToolsClient, ToolsAsyncClient]) +@mock.patch.object( + ToolsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ToolsClient) +) +@mock.patch.object( + ToolsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ToolsAsyncClient) +) +def test_tools_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [ToolsClient, ToolsAsyncClient]) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test_tools_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ToolsClient._DEFAULT_UNIVERSE + default_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc"), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (ToolsClient, transports.ToolsRestTransport, "rest"), + ], +) +def test_tools_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", grpc_helpers), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ToolsClient, transports.ToolsRestTransport, "rest", None), + ], +) +def test_tools_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_tools_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflowcx_v3.services.tools.transports.ToolsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ToolsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", grpc_helpers), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_tools_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_tool.CreateToolRequest, + dict, + ], +) +def test_create_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + response = client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_tool.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +def test_create_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_tool.CreateToolRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_tool.CreateToolRequest( + parent="parent_value", + ) + + +def test_create_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_tool] = mock_rpc + request = {} + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_tool + ] = mock_rpc + + request = {} + await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_async( + transport: str = "grpc_asyncio", request_type=gcdc_tool.CreateToolRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + response = await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_tool.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.asyncio +async def test_create_tool_async_from_dict(): + await test_create_tool_async(request_type=dict) + + +def test_create_tool_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_tool.CreateToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = gcdc_tool.Tool() + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_tool_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_tool.CreateToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_tool.Tool()) + await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_tool_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tool( + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool + mock_val = gcdc_tool.Tool(name="name_value") + assert arg == mock_val + + +def test_create_tool_flattened_error(): + client = ToolsClient( + credentials=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_tool( + gcdc_tool.CreateToolRequest(), + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_tool_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tool( + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool + mock_val = gcdc_tool.Tool(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_tool_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tool( + gcdc_tool.CreateToolRequest(), + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolsRequest, + dict, + ], +) +def test_list_tools(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.ListToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_tools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.ListToolsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_tools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.ListToolsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_tools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_tools] = mock_rpc + request = {} + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_tools + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_tools + ] = mock_rpc + + request = {} + await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tools_async( + transport: str = "grpc_asyncio", request_type=tool.ListToolsRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.ListToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_tools_async_from_dict(): + await test_list_tools_async(request_type=dict) + + +def test_list_tools_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.ListToolsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = tool.ListToolsResponse() + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_tools_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.ListToolsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolsResponse() + ) + await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_tools_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tools( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_tools_flattened_error(): + client = ToolsClient( + credentials=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_tools( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_tools_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tools( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_tools_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tools( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_pager(transport_name: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_tools(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.Tool) for i in results) + + +def test_list_tools_pages(transport_name: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tools(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_tools_async_pager(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tools), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tools( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, tool.Tool) for i in responses) + + +@pytest.mark.asyncio +async def test_list_tools_async_pages(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tools), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_tools(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolRequest, + dict, + ], +) +def test_get_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + response = client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.GetToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL + + +def test_get_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.GetToolRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.GetToolRequest( + name="name_value", + ) + + +def test_get_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc + request = {} + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_tool + ] = mock_rpc + + request = {} + await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_async( + transport: str = "grpc_asyncio", request_type=tool.GetToolRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + response = await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.GetToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.asyncio +async def test_get_tool_async_from_dict(): + await test_get_tool_async(request_type=dict) + + +def test_get_tool_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.GetToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = tool.Tool() + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_tool_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.GetToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.Tool()) + await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_tool_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_tool_flattened_error(): + client = ToolsClient( + credentials=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_tool( + tool.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_tool_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_tool_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tool( + tool.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_tool.UpdateToolRequest, + dict, + ], +) +def test_update_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + response = client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcdc_tool.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +def test_update_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcdc_tool.UpdateToolRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_tool.UpdateToolRequest() + + +def test_update_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc + request = {} + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_tool + ] = mock_rpc + + request = {} + await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_tool_async( + transport: str = "grpc_asyncio", request_type=gcdc_tool.UpdateToolRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + response = await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcdc_tool.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.asyncio +async def test_update_tool_async_from_dict(): + await test_update_tool_async(request_type=dict) + + +def test_update_tool_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_tool.UpdateToolRequest() + + request.tool.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = gcdc_tool.Tool() + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tool.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_tool_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_tool.UpdateToolRequest() + + request.tool.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_tool.Tool()) + await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tool.name=name_value", + ) in kw["metadata"] + + +def test_update_tool_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tool( + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].tool + mock_val = gcdc_tool.Tool(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_tool_flattened_error(): + client = ToolsClient( + credentials=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_tool( + gcdc_tool.UpdateToolRequest(), + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_tool_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tool( + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].tool + mock_val = gcdc_tool.Tool(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_tool_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tool( + gcdc_tool.UpdateToolRequest(), + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.DeleteToolRequest, + dict, + ], +) +def test_delete_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.DeleteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.DeleteToolRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.DeleteToolRequest( + name="name_value", + ) + + +def test_delete_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc + request = {} + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_tool + ] = mock_rpc + + request = {} + await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_async( + transport: str = "grpc_asyncio", request_type=tool.DeleteToolRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.DeleteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tool_async_from_dict(): + await test_delete_tool_async(request_type=dict) + + +def test_delete_tool_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.DeleteToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = None + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_tool_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.DeleteToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_tool_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__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_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_tool_flattened_error(): + client = ToolsClient( + credentials=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_tool( + tool.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_tool_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__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_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_tool_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tool( + tool.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolVersionsRequest, + dict, + ], +) +def test_list_tool_versions(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolVersionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_tool_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.ListToolVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_tool_versions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.ListToolVersionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_tool_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.ListToolVersionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_tool_versions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_tool_versions in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_tool_versions + ] = mock_rpc + request = {} + client.list_tool_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tool_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tool_versions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_tool_versions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_tool_versions + ] = mock_rpc + + request = {} + await client.list_tool_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_tool_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tool_versions_async( + transport: str = "grpc_asyncio", request_type=tool.ListToolVersionsRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_tool_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.ListToolVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolVersionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_tool_versions_async_from_dict(): + await test_list_tool_versions_async(request_type=dict) + + +def test_list_tool_versions_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.ListToolVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + call.return_value = tool.ListToolVersionsResponse() + client.list_tool_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_tool_versions_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.ListToolVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolVersionsResponse() + ) + await client.list_tool_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_tool_versions_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tool_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_tool_versions_flattened_error(): + client = ToolsClient( + credentials=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_tool_versions( + tool.ListToolVersionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_tool_versions_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ListToolVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tool_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_tool_versions_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tool_versions( + tool.ListToolVersionsRequest(), + parent="parent_value", + ) + + +def test_list_tool_versions_pager(transport_name: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + tool.ToolVersion(), + ], + next_page_token="abc", + ), + tool.ListToolVersionsResponse( + tool_versions=[], + next_page_token="def", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + ], + next_page_token="ghi", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_tool_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.ToolVersion) for i in results) + + +def test_list_tool_versions_pages(transport_name: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + tool.ToolVersion(), + ], + next_page_token="abc", + ), + tool.ListToolVersionsResponse( + tool_versions=[], + next_page_token="def", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + ], + next_page_token="ghi", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tool_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_tool_versions_async_pager(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + tool.ToolVersion(), + ], + next_page_token="abc", + ), + tool.ListToolVersionsResponse( + tool_versions=[], + next_page_token="def", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + ], + next_page_token="ghi", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tool_versions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, tool.ToolVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_tool_versions_async_pages(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + tool.ToolVersion(), + ], + next_page_token="abc", + ), + tool.ListToolVersionsResponse( + tool_versions=[], + next_page_token="def", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + ], + next_page_token="ghi", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_tool_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + tool.CreateToolVersionRequest, + dict, + ], +) +def test_create_tool_version(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + response = client.create_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.CreateToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_create_tool_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.CreateToolVersionRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_tool_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.CreateToolVersionRequest( + parent="parent_value", + ) + + +def test_create_tool_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_tool_version + ] = mock_rpc + request = {} + client.create_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_tool_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_tool_version + ] = mock_rpc + + request = {} + await client.create_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_version_async( + transport: str = "grpc_asyncio", request_type=tool.CreateToolVersionRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.create_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.CreateToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_create_tool_version_async_from_dict(): + await test_create_tool_version_async(request_type=dict) + + +def test_create_tool_version_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.CreateToolVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + call.return_value = tool.ToolVersion() + client.create_tool_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_tool_version_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.CreateToolVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.ToolVersion()) + await client.create_tool_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_tool_version_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tool_version( + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool_version + mock_val = tool.ToolVersion(name="name_value") + assert arg == mock_val + + +def test_create_tool_version_flattened_error(): + client = ToolsClient( + credentials=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_tool_version( + tool.CreateToolVersionRequest(), + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_tool_version_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.ToolVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tool_version( + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool_version + mock_val = tool.ToolVersion(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_tool_version_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tool_version( + tool.CreateToolVersionRequest(), + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolVersionRequest, + dict, + ], +) +def test_get_tool_version(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + response = client.get_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.GetToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_get_tool_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.GetToolVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_tool_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.GetToolVersionRequest( + name="name_value", + ) + + +def test_get_tool_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_tool_version + ] = mock_rpc + request = {} + client.get_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_tool_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_tool_version + ] = mock_rpc + + request = {} + await client.get_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_version_async( + transport: str = "grpc_asyncio", request_type=tool.GetToolVersionRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.get_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.GetToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_get_tool_version_async_from_dict(): + await test_get_tool_version_async(request_type=dict) + + +def test_get_tool_version_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.GetToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + call.return_value = tool.ToolVersion() + client.get_tool_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_tool_version_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.GetToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.ToolVersion()) + await client.get_tool_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_tool_version_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_tool_version_flattened_error(): + client = ToolsClient( + credentials=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_tool_version( + tool.GetToolVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_tool_version_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.ToolVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.ToolVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_tool_version_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tool_version( + tool.GetToolVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.DeleteToolVersionRequest, + dict, + ], +) +def test_delete_tool_version(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.DeleteToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tool_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.DeleteToolVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_tool_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.DeleteToolVersionRequest( + name="name_value", + ) + + +def test_delete_tool_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_tool_version + ] = mock_rpc + request = {} + client.delete_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_tool_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_tool_version + ] = mock_rpc + + request = {} + await client.delete_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_version_async( + transport: str = "grpc_asyncio", request_type=tool.DeleteToolVersionRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.DeleteToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tool_version_async_from_dict(): + await test_delete_tool_version_async(request_type=dict) + + +def test_delete_tool_version_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.DeleteToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + call.return_value = None + client.delete_tool_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_tool_version_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.DeleteToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool_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_tool_version_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_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_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_tool_version_flattened_error(): + client = ToolsClient( + credentials=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_tool_version( + tool.DeleteToolVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_tool_version_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_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_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_tool_version_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tool_version( + tool.DeleteToolVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.RestoreToolVersionRequest, + dict, + ], +) +def test_restore_tool_version(request_type, transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.RestoreToolVersionResponse() + response = client.restore_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool.RestoreToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.RestoreToolVersionResponse) + + +def test_restore_tool_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool.RestoreToolVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.restore_tool_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool.RestoreToolVersionRequest( + name="name_value", + ) + + +def test_restore_tool_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restore_tool_version + ] = mock_rpc + request = {} + client.restore_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_tool_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.restore_tool_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.restore_tool_version + ] = mock_rpc + + request = {} + await client.restore_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.restore_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_tool_version_async( + transport: str = "grpc_asyncio", request_type=tool.RestoreToolVersionRequest +): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.RestoreToolVersionResponse() + ) + response = await client.restore_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool.RestoreToolVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.RestoreToolVersionResponse) + + +@pytest.mark.asyncio +async def test_restore_tool_version_async_from_dict(): + await test_restore_tool_version_async(request_type=dict) + + +def test_restore_tool_version_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.RestoreToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + call.return_value = tool.RestoreToolVersionResponse() + client.restore_tool_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_restore_tool_version_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool.RestoreToolVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.RestoreToolVersionResponse() + ) + await client.restore_tool_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_restore_tool_version_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.RestoreToolVersionResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_restore_tool_version_flattened_error(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_tool_version( + tool.RestoreToolVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_restore_tool_version_flattened_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool.RestoreToolVersionResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.RestoreToolVersionResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_tool_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_restore_tool_version_flattened_error_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_tool_version( + tool.RestoreToolVersionRequest(), + name="name_value", + ) + + +def test_create_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_tool] = mock_rpc + + request = {} + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_tool_rest_required_fields(request_type=gcdc_tool.CreateToolRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_tool_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_tool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "tool", + ) + ) + ) + + +def test_create_tool_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*}/tools" + % client.transport._host, + args[1], + ) + + +def test_create_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_tool( + gcdc_tool.CreateToolRequest(), + parent="parent_value", + tool=gcdc_tool.Tool(name="name_value"), + ) + + +def test_list_tools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_tools] = mock_rpc + + request = {} + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_tools_rest_required_fields(request_type=tool.ListToolsRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.ListToolsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_tools(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tools_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tools._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_tools_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ListToolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_tools(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*}/tools" + % client.transport._host, + args[1], + ) + + +def test_list_tools_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tools( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_rest_pager(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tool.ListToolsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + + pager = client.list_tools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.Tool) for i in results) + + pages = list(client.list_tools(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc + + request = {} + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_tool_rest_required_fields(request_type=tool.GetToolRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_tool_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_tool_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_get_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_tool( + tool.GetToolRequest(), + name="name_value", + ) + + +def test_update_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc + + request = {} + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_tool_rest_required_fields(request_type=gcdc_tool.UpdateToolRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_tool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_tool_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("tool",))) + + +def test_update_tool_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = { + "tool": { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{tool.name=projects/*/locations/*/agents/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_update_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_tool( + gcdc_tool.UpdateToolRequest(), + tool=gcdc_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc + + request = {} + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_tool_rest_required_fields(request_type=tool.DeleteToolRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_tool_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +def test_delete_tool_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tool( + tool.DeleteToolRequest(), + name="name_value", + ) + + +def test_list_tool_versions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_tool_versions in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_tool_versions + ] = mock_rpc + + request = {} + client.list_tool_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tool_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_tool_versions_rest_required_fields( + request_type=tool.ListToolVersionsRequest, +): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tool_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tool_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.ListToolVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ListToolVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_tool_versions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tool_versions_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tool_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_tool_versions_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ListToolVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.ListToolVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_tool_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/tools/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_list_tool_versions_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tool_versions( + tool.ListToolVersionsRequest(), + parent="parent_value", + ) + + +def test_list_tool_versions_rest_pager(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + tool.ToolVersion(), + ], + next_page_token="abc", + ), + tool.ListToolVersionsResponse( + tool_versions=[], + next_page_token="def", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + ], + next_page_token="ghi", + ), + tool.ListToolVersionsResponse( + tool_versions=[ + tool.ToolVersion(), + tool.ToolVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tool.ListToolVersionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + + pager = client.list_tool_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.ToolVersion) for i in results) + + pages = list(client.list_tool_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_tool_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_tool_version + ] = mock_rpc + + request = {} + client.create_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_tool_version_rest_required_fields( + request_type=tool.CreateToolVersionRequest, +): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_tool_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_tool_version_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_tool_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "toolVersion", + ) + ) + ) + + +def test_create_tool_version_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_tool_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{parent=projects/*/locations/*/agents/*/tools/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_create_tool_version_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_tool_version( + tool.CreateToolVersionRequest(), + parent="parent_value", + tool_version=tool.ToolVersion(name="name_value"), + ) + + +def test_get_tool_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_tool_version + ] = mock_rpc + + request = {} + client.get_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_tool_version_rest_required_fields(request_type=tool.GetToolVersionRequest): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_tool_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_tool_version_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_tool_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_tool_version_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_tool_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_tool_version_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_tool_version( + tool.GetToolVersionRequest(), + name="name_value", + ) + + +def test_delete_tool_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_tool_version + ] = mock_rpc + + request = {} + client.delete_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_tool_version_rest_required_fields( + request_type=tool.DeleteToolVersionRequest, +): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_tool_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_tool_version_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tool_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +def test_delete_tool_version_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_tool_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_tool_version_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tool_version( + tool.DeleteToolVersionRequest(), + name="name_value", + ) + + +def test_restore_tool_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_tool_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restore_tool_version + ] = mock_rpc + + request = {} + client.restore_tool_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_tool_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_tool_version_rest_required_fields( + request_type=tool.RestoreToolVersionRequest, +): + transport_class = transports.ToolsRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_tool_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.RestoreToolVersionResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.RestoreToolVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.restore_tool_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_tool_version_rest_unset_required_fields(): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_tool_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_restore_tool_version_rest_flattened(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.RestoreToolVersionResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.RestoreToolVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.restore_tool_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v3/{name=projects/*/locations/*/agents/*/tools/*/versions/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_tool_version_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_tool_version( + tool.RestoreToolVersionRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ToolsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ToolsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ToolsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ToolsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + transports.ToolsRestTransport, + ], +) +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_kind_grpc(): + transport = ToolsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = gcdc_tool.Tool() + client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tools_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = tool.ListToolsResponse() + client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = tool.Tool() + client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tool_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = gcdc_tool.Tool() + client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = None + client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tool_versions_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + call.return_value = tool.ListToolVersionsResponse() + client.list_tool_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_version_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + call.return_value = tool.ToolVersion() + client.create_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.CreateToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_version_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + call.return_value = tool.ToolVersion() + client.get_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_version_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + call.return_value = None + client.delete_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_tool_version_empty_call_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + call.return_value = tool.RestoreToolVersionResponse() + client.restore_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.RestoreToolVersionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ToolsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + await client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tools_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + await client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + ) + await client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tool_versions_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ListToolVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tool_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tool_version_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + ) + await client.create_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.CreateToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_tool_version_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + ) + await client.get_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tool_version_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_tool_version_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.RestoreToolVersionResponse() + ) + await client.restore_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.RestoreToolVersionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ToolsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_tool_rest_bad_request(request_type=gcdc_tool.CreateToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_tool.CreateToolRequest, + dict, + ], +) +def test_create_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request_init["tool"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "open_api_spec": { + "text_schema": "text_schema_value", + "authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key": "api_key_value", + "secret_version_for_api_key": "secret_version_for_api_key_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_auth_config": {"service_agent_auth": 1}, + "bearer_token_config": { + "token": "token_value", + "secret_version_for_token": "secret_version_for_token_value", + }, + "service_account_auth_config": { + "service_account": "service_account_value" + }, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + }, + "data_store_spec": { + "data_store_connections": [ + { + "data_store_type": 1, + "data_store": "data_store_value", + "document_processing_mode": 1, + } + ], + "fallback_prompt": {}, + }, + "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}}, + "tool_type": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_tool.CreateToolRequest.meta.fields["tool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tool"][field])): + del request_init["tool"][field][i][subfield] + else: + del request_init["tool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_create_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_create_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_create_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_tool.CreateToolRequest.pb(gcdc_tool.CreateToolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_tool.Tool.to_json(gcdc_tool.Tool()) + req.return_value.content = return_value + + request = gcdc_tool.CreateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_tool.Tool() + post_with_metadata.return_value = gcdc_tool.Tool(), metadata + + client.create_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_tools_rest_bad_request(request_type=tool.ListToolsRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_tools(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolsRequest, + dict, + ], +) +def test_list_tools_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ListToolsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_tools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tools_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_list_tools" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_list_tools_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_list_tools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.ListToolsRequest.pb(tool.ListToolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.ListToolsResponse.to_json(tool.ListToolsResponse()) + req.return_value.content = return_value + + request = tool.ListToolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.ListToolsResponse() + post_with_metadata.return_value = tool.ListToolsResponse(), metadata + + client.list_tools( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_tool_rest_bad_request(request_type=tool.GetToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolRequest, + dict, + ], +) +def test_get_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_get_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_get_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_get_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.GetToolRequest.pb(tool.GetToolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.Tool.to_json(tool.Tool()) + req.return_value.content = return_value + + request = tool.GetToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.Tool() + post_with_metadata.return_value = tool.Tool(), metadata + + client.get_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_tool_rest_bad_request(request_type=gcdc_tool.UpdateToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "tool": { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcdc_tool.UpdateToolRequest, + dict, + ], +) +def test_update_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "tool": { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + } + request_init["tool"] = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4", + "display_name": "display_name_value", + "description": "description_value", + "open_api_spec": { + "text_schema": "text_schema_value", + "authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key": "api_key_value", + "secret_version_for_api_key": "secret_version_for_api_key_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_auth_config": {"service_agent_auth": 1}, + "bearer_token_config": { + "token": "token_value", + "secret_version_for_token": "secret_version_for_token_value", + }, + "service_account_auth_config": { + "service_account": "service_account_value" + }, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + }, + "data_store_spec": { + "data_store_connections": [ + { + "data_store_type": 1, + "data_store": "data_store_value", + "document_processing_mode": 1, + } + ], + "fallback_prompt": {}, + }, + "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}}, + "tool_type": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcdc_tool.UpdateToolRequest.meta.fields["tool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tool"][field])): + del request_init["tool"][field][i][subfield] + else: + del request_init["tool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcdc_tool.Tool( + name="name_value", + display_name="display_name_value", + description="description_value", + tool_type=gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcdc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tool_type == gcdc_tool.Tool.ToolType.CUSTOMIZED_TOOL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_update_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_update_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_update_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcdc_tool.UpdateToolRequest.pb(gcdc_tool.UpdateToolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcdc_tool.Tool.to_json(gcdc_tool.Tool()) + req.return_value.content = return_value + + request = gcdc_tool.UpdateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcdc_tool.Tool() + post_with_metadata.return_value = gcdc_tool.Tool(), metadata + + client.update_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_tool_rest_bad_request(request_type=tool.DeleteToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.DeleteToolRequest, + dict, + ], +) +def test_delete_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_tool(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "pre_delete_tool" + ) as pre: + pre.assert_not_called() + pb_message = tool.DeleteToolRequest.pb(tool.DeleteToolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = tool.DeleteToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_tool_versions_rest_bad_request(request_type=tool.ListToolVersionsRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_tool_versions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolVersionsRequest, + dict, + ], +) +def test_list_tool_versions_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ListToolVersionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ListToolVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_tool_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tool_versions_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_list_tool_versions" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_list_tool_versions_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_list_tool_versions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.ListToolVersionsRequest.pb(tool.ListToolVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.ListToolVersionsResponse.to_json( + tool.ListToolVersionsResponse() + ) + req.return_value.content = return_value + + request = tool.ListToolVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.ListToolVersionsResponse() + post_with_metadata.return_value = tool.ListToolVersionsResponse(), metadata + + client.list_tool_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_tool_version_rest_bad_request( + request_type=tool.CreateToolVersionRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_tool_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.CreateToolVersionRequest, + dict, + ], +) +def test_create_tool_version_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/agents/sample3/tools/sample4" + } + request_init["tool_version"] = { + "name": "name_value", + "display_name": "display_name_value", + "tool": { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "open_api_spec": { + "text_schema": "text_schema_value", + "authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key": "api_key_value", + "secret_version_for_api_key": "secret_version_for_api_key_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_auth_config": {"service_agent_auth": 1}, + "bearer_token_config": { + "token": "token_value", + "secret_version_for_token": "secret_version_for_token_value", + }, + "service_account_auth_config": { + "service_account": "service_account_value" + }, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + }, + "data_store_spec": { + "data_store_connections": [ + { + "data_store_type": 1, + "data_store": "data_store_value", + "document_processing_mode": 1, + } + ], + "fallback_prompt": {}, + }, + "function_spec": {"input_schema": {"fields": {}}, "output_schema": {}}, + "tool_type": 1, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tool.CreateToolVersionRequest.meta.fields["tool_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tool_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tool_version"][field])): + del request_init["tool_version"][field][i][subfield] + else: + del request_init["tool_version"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_tool_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tool_version_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_create_tool_version" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_create_tool_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_create_tool_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.CreateToolVersionRequest.pb(tool.CreateToolVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.ToolVersion.to_json(tool.ToolVersion()) + req.return_value.content = return_value + + request = tool.CreateToolVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.ToolVersion() + post_with_metadata.return_value = tool.ToolVersion(), metadata + + client.create_tool_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_tool_version_rest_bad_request(request_type=tool.GetToolVersionRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_tool_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolVersionRequest, + dict, + ], +) +def test_get_tool_version_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.ToolVersion( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.ToolVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_tool_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.ToolVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tool_version_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_get_tool_version" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_get_tool_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_get_tool_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.GetToolVersionRequest.pb(tool.GetToolVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.ToolVersion.to_json(tool.ToolVersion()) + req.return_value.content = return_value + + request = tool.GetToolVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.ToolVersion() + post_with_metadata.return_value = tool.ToolVersion(), metadata + + client.get_tool_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_tool_version_rest_bad_request( + request_type=tool.DeleteToolVersionRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_tool_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.DeleteToolVersionRequest, + dict, + ], +) +def test_delete_tool_version_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_tool_version(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tool_version_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "pre_delete_tool_version" + ) as pre: + pre.assert_not_called() + pb_message = tool.DeleteToolVersionRequest.pb(tool.DeleteToolVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = tool.DeleteToolVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_tool_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_restore_tool_version_rest_bad_request( + request_type=tool.RestoreToolVersionRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.restore_tool_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.RestoreToolVersionRequest, + dict, + ], +) +def test_restore_tool_version_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/agents/sample3/tools/sample4/versions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.RestoreToolVersionResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.RestoreToolVersionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.restore_tool_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.RestoreToolVersionResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_tool_version_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolsRestInterceptor, "post_restore_tool_version" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_restore_tool_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_restore_tool_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.RestoreToolVersionRequest.pb(tool.RestoreToolVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.RestoreToolVersionResponse.to_json( + tool.RestoreToolVersionResponse() + ) + req.return_value.content = return_value + + request = tool.RestoreToolVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.RestoreToolVersionResponse() + post_with_metadata.return_value = tool.RestoreToolVersionResponse(), metadata + + client.restore_tool_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tools_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tool_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcdc_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tool_versions_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tool_versions), "__call__" + ) as call: + client.list_tool_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.ListToolVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_version_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tool_version), "__call__" + ) as call: + client.create_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.CreateToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_version_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool_version), "__call__") as call: + client.get_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.GetToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_version_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tool_version), "__call__" + ) as call: + client.delete_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.DeleteToolVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_tool_version_empty_call_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_tool_version), "__call__" + ) as call: + client.restore_tool_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.RestoreToolVersionRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ToolsGrpcTransport, + ) + + +def test_tools_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ToolsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_tools_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflowcx_v3.services.tools.transports.ToolsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ToolsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_tool", + "list_tools", + "get_tool", + "update_tool", + "delete_tool", + "list_tool_versions", + "create_tool_version", + "get_tool_version", + "delete_tool_version", + "restore_tool_version", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_tools_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.tools.transports.ToolsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_tools_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.tools.transports.ToolsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolsTransport() + adc.assert_called_once() + + +def test_tools_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) + ToolsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + ], +) +def test_tools_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.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + transports.ToolsRestTransport, + ], +) +def test_tools_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ToolsGrpcTransport, grpc_helpers), + (transports.ToolsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_tools_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_tools_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ToolsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_tools_host_no_port(transport_name): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_tools_host_with_port(transport_name): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_tools_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ToolsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ToolsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_tool._session + session2 = client2.transport.create_tool._session + assert session1 != session2 + session1 = client1.transport.list_tools._session + session2 = client2.transport.list_tools._session + assert session1 != session2 + session1 = client1.transport.get_tool._session + session2 = client2.transport.get_tool._session + assert session1 != session2 + session1 = client1.transport.update_tool._session + session2 = client2.transport.update_tool._session + assert session1 != session2 + session1 = client1.transport.delete_tool._session + session2 = client2.transport.delete_tool._session + assert session1 != session2 + session1 = client1.transport.list_tool_versions._session + session2 = client2.transport.list_tool_versions._session + assert session1 != session2 + session1 = client1.transport.create_tool_version._session + session2 = client2.transport.create_tool_version._session + assert session1 != session2 + session1 = client1.transport.get_tool_version._session + session2 = client2.transport.get_tool_version._session + assert session1 != session2 + session1 = client1.transport.delete_tool_version._session + session2 = client2.transport.delete_tool_version._session + assert session1 != session2 + session1 = client1.transport.restore_tool_version._session + session2 = client2.transport.restore_tool_version._session + assert session1 != session2 + + +def test_tools_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolsGrpcTransport( + 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_tools_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolsGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_secret_version_path(): + project = "squid" + secret = "clam" + version = "whelk" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + actual = ToolsClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "octopus", + "secret": "oyster", + "version": "nudibranch", + } + path = ToolsClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_secret_version_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + actual = ToolsClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", + } + path = ToolsClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_service_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + tool = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = ToolsClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "tool": "nautilus", + } + path = ToolsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_tool_path(path) + assert expected == actual + + +def test_tool_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + tool = "clam" + version = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}/versions/{version}".format( + project=project, + location=location, + agent=agent, + tool=tool, + version=version, + ) + actual = ToolsClient.tool_version_path(project, location, agent, tool, version) + assert expected == actual + + +def test_parse_tool_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "tool": "cuttlefish", + "version": "mussel", + } + path = ToolsClient.tool_version_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_tool_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 = ToolsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ToolsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ToolsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ToolsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ToolsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ToolsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = ToolsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ToolsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.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 = ToolsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ToolsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep: + transport_class = ToolsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = ToolsClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = ToolsAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ToolsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ToolsClient, transports.ToolsGrpcTransport), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py index e92a63f1aefc..bfb58fc4534c 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py @@ -69,6 +69,7 @@ gcs, page, response_message, + tool_call, ) from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, @@ -5166,6 +5167,11 @@ def test_create_transition_route_group_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -5493,6 +5499,11 @@ def test_update_transition_route_group_rest_call_success(request_type): "phone_number": "phone_number_value" }, "knowledge_info_card": {}, + "tool_call": { + "tool": "tool_value", + "action": "action_value", + "input_parameters": {}, + }, "response_type": 1, "channel": "channel_value", } @@ -6850,12 +6861,43 @@ def test_parse_page_path(): assert expected == actual -def test_transition_route_group_path(): +def test_tool_path(): project = "scallop" location = "abalone" agent = "squid" - flow = "clam" - transition_route_group = "whelk" + tool = "clam" + expected = ( + "projects/{project}/locations/{location}/agents/{agent}/tools/{tool}".format( + project=project, + location=location, + agent=agent, + tool=tool, + ) + ) + actual = TransitionRouteGroupsClient.tool_path(project, location, agent, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "tool": "nudibranch", + } + path = TransitionRouteGroupsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_tool_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, @@ -6871,11 +6913,11 @@ def test_transition_route_group_path(): def test_parse_transition_route_group_path(): expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "transition_route_group": "mussel", + "project": "abalone", + "location": "squid", + "agent": "clam", + "flow": "whelk", + "transition_route_group": "octopus", } path = TransitionRouteGroupsClient.transition_route_group_path(**expected) @@ -6885,10 +6927,10 @@ def test_parse_transition_route_group_path(): def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + webhook = "mussel" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -6901,10 +6943,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "webhook": "abalone", } path = TransitionRouteGroupsClient.webhook_path(**expected) @@ -6914,7 +6956,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6924,7 +6966,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "clam", } path = TransitionRouteGroupsClient.common_billing_account_path(**expected) @@ -6934,7 +6976,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -6944,7 +6986,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "octopus", } path = TransitionRouteGroupsClient.common_folder_path(**expected) @@ -6954,7 +6996,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -6964,7 +7006,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "nudibranch", } path = TransitionRouteGroupsClient.common_organization_path(**expected) @@ -6974,7 +7016,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -6984,7 +7026,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "mussel", } path = TransitionRouteGroupsClient.common_project_path(**expected) @@ -6994,8 +7036,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -7006,8 +7048,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "scallop", + "location": "abalone", } path = TransitionRouteGroupsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py index a9aca2403071..a09bcfe73b84 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py @@ -4736,15 +4736,19 @@ def test_create_webhook_rest_call_success(request_type): "uri": "uri_value", "username": "username_value", "password": "password_value", + "secret_version_for_username_password": "secret_version_for_username_password_value", "request_headers": {}, + "secret_versions_for_request_headers": {}, "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"], "oauth_config": { "client_id": "client_id_value", "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", "token_endpoint": "token_endpoint_value", "scopes": ["scopes_value1", "scopes_value2"], }, "service_agent_auth": 1, + "service_account_auth_config": {"service_account": "service_account_value"}, "webhook_type": 1, "http_method": 1, "request_body": "request_body_value", @@ -4965,15 +4969,19 @@ def test_update_webhook_rest_call_success(request_type): "uri": "uri_value", "username": "username_value", "password": "password_value", + "secret_version_for_username_password": "secret_version_for_username_password_value", "request_headers": {}, + "secret_versions_for_request_headers": {}, "allowed_ca_certs": [b"allowed_ca_certs_blob1", b"allowed_ca_certs_blob2"], "oauth_config": { "client_id": "client_id_value", "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", "token_endpoint": "token_endpoint_value", "scopes": ["scopes_value1", "scopes_value2"], }, "service_agent_auth": 1, + "service_account_auth_config": {"service_account": "service_account_value"}, "webhook_type": 1, "http_method": 1, "request_body": "request_body_value", @@ -6104,11 +6112,37 @@ def test_webhooks_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_service_path(): +def test_secret_version_path(): project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" + secret = "clam" + version = "whelk" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + actual = WebhooksClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "octopus", + "secret": "oyster", + "version": "nudibranch", + } + path = WebhooksClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_secret_version_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( project=project, location=location, @@ -6121,10 +6155,10 @@ def test_service_path(): def test_parse_service_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "namespace": "cuttlefish", - "service": "mussel", + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", } path = WebhooksClient.service_path(**expected) @@ -6134,10 +6168,10 @@ def test_parse_service_path(): def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" + project = "whelk" + location = "octopus" + agent = "oyster" + webhook = "nudibranch" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, @@ -6150,10 +6184,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "webhook": "nautilus", } path = WebhooksClient.webhook_path(**expected) @@ -6163,7 +6197,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6173,7 +6207,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = WebhooksClient.common_billing_account_path(**expected) @@ -6183,7 +6217,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -6193,7 +6227,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = WebhooksClient.common_folder_path(**expected) @@ -6203,7 +6237,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -6213,7 +6247,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = WebhooksClient.common_organization_path(**expected) @@ -6223,7 +6257,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -6233,7 +6267,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = WebhooksClient.common_project_path(**expected) @@ -6243,8 +6277,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -6255,8 +6289,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = WebhooksClient.common_location_path(**expected) diff --git a/packages/google-cloud-kms/docs/kms_v1/hsm_management.rst b/packages/google-cloud-kms/docs/kms_v1/hsm_management.rst new file mode 100644 index 000000000000..7416e5f73d29 --- /dev/null +++ b/packages/google-cloud-kms/docs/kms_v1/hsm_management.rst @@ -0,0 +1,10 @@ +HsmManagement +------------------------------- + +.. automodule:: google.cloud.kms_v1.services.hsm_management + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.hsm_management.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-kms/docs/kms_v1/services_.rst b/packages/google-cloud-kms/docs/kms_v1/services_.rst index 18fe1076d51a..bebed58d4249 100644 --- a/packages/google-cloud-kms/docs/kms_v1/services_.rst +++ b/packages/google-cloud-kms/docs/kms_v1/services_.rst @@ -6,4 +6,5 @@ Services for Google Cloud Kms v1 API autokey autokey_admin ekm_service + hsm_management key_management_service diff --git a/packages/google-cloud-kms/google/cloud/kms/__init__.py b/packages/google-cloud-kms/google/cloud/kms/__init__.py index 79df5c0dd235..922e16b10a52 100644 --- a/packages/google-cloud-kms/google/cloud/kms/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms/__init__.py @@ -26,6 +26,10 @@ from google.cloud.kms_v1.services.autokey_admin.client import AutokeyAdminClient from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient from google.cloud.kms_v1.services.ekm_service.client import EkmServiceClient +from google.cloud.kms_v1.services.hsm_management.async_client import ( + HsmManagementAsyncClient, +) +from google.cloud.kms_v1.services.hsm_management.client import HsmManagementClient from google.cloud.kms_v1.services.key_management_service.async_client import ( KeyManagementServiceAsyncClient, ) @@ -61,6 +65,28 @@ VerifyConnectivityRequest, VerifyConnectivityResponse, ) +from google.cloud.kms_v1.types.hsm_management import ( + ApproveSingleTenantHsmInstanceProposalRequest, + ApproveSingleTenantHsmInstanceProposalResponse, + Challenge, + ChallengeReply, + CreateSingleTenantHsmInstanceMetadata, + CreateSingleTenantHsmInstanceProposalMetadata, + CreateSingleTenantHsmInstanceProposalRequest, + CreateSingleTenantHsmInstanceRequest, + DeleteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalMetadata, + ExecuteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalResponse, + GetSingleTenantHsmInstanceProposalRequest, + GetSingleTenantHsmInstanceRequest, + ListSingleTenantHsmInstanceProposalsRequest, + ListSingleTenantHsmInstanceProposalsResponse, + ListSingleTenantHsmInstancesRequest, + ListSingleTenantHsmInstancesResponse, + SingleTenantHsmInstance, + SingleTenantHsmInstanceProposal, +) from google.cloud.kms_v1.types.resources import ( AccessReason, ChecksummedData, @@ -130,6 +156,8 @@ "AutokeyAdminAsyncClient", "EkmServiceClient", "EkmServiceAsyncClient", + "HsmManagementClient", + "HsmManagementAsyncClient", "KeyManagementServiceClient", "KeyManagementServiceAsyncClient", "CreateKeyHandleMetadata", @@ -155,6 +183,26 @@ "UpdateEkmConnectionRequest", "VerifyConnectivityRequest", "VerifyConnectivityResponse", + "ApproveSingleTenantHsmInstanceProposalRequest", + "ApproveSingleTenantHsmInstanceProposalResponse", + "Challenge", + "ChallengeReply", + "CreateSingleTenantHsmInstanceMetadata", + "CreateSingleTenantHsmInstanceProposalMetadata", + "CreateSingleTenantHsmInstanceProposalRequest", + "CreateSingleTenantHsmInstanceRequest", + "DeleteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalMetadata", + "ExecuteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalResponse", + "GetSingleTenantHsmInstanceProposalRequest", + "GetSingleTenantHsmInstanceRequest", + "ListSingleTenantHsmInstanceProposalsRequest", + "ListSingleTenantHsmInstanceProposalsResponse", + "ListSingleTenantHsmInstancesRequest", + "ListSingleTenantHsmInstancesResponse", + "SingleTenantHsmInstance", + "SingleTenantHsmInstanceProposal", "ChecksummedData", "CryptoKey", "CryptoKeyVersion", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py index ed7069fe2952..c0d6c2ba0736 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py @@ -31,6 +31,7 @@ from .services.autokey import AutokeyAsyncClient, AutokeyClient from .services.autokey_admin import AutokeyAdminAsyncClient, AutokeyAdminClient from .services.ekm_service import EkmServiceAsyncClient, EkmServiceClient +from .services.hsm_management import HsmManagementAsyncClient, HsmManagementClient from .services.key_management_service import ( KeyManagementServiceAsyncClient, KeyManagementServiceClient, @@ -64,6 +65,28 @@ VerifyConnectivityRequest, VerifyConnectivityResponse, ) +from .types.hsm_management import ( + ApproveSingleTenantHsmInstanceProposalRequest, + ApproveSingleTenantHsmInstanceProposalResponse, + Challenge, + ChallengeReply, + CreateSingleTenantHsmInstanceMetadata, + CreateSingleTenantHsmInstanceProposalMetadata, + CreateSingleTenantHsmInstanceProposalRequest, + CreateSingleTenantHsmInstanceRequest, + DeleteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalMetadata, + ExecuteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalResponse, + GetSingleTenantHsmInstanceProposalRequest, + GetSingleTenantHsmInstanceRequest, + ListSingleTenantHsmInstanceProposalsRequest, + ListSingleTenantHsmInstanceProposalsResponse, + ListSingleTenantHsmInstancesRequest, + ListSingleTenantHsmInstancesResponse, + SingleTenantHsmInstance, + SingleTenantHsmInstanceProposal, +) from .types.resources import ( AccessReason, ChecksummedData, @@ -224,8 +247,11 @@ def _get_version(dependency_name): "AutokeyAdminAsyncClient", "AutokeyAsyncClient", "EkmServiceAsyncClient", + "HsmManagementAsyncClient", "KeyManagementServiceAsyncClient", "AccessReason", + "ApproveSingleTenantHsmInstanceProposalRequest", + "ApproveSingleTenantHsmInstanceProposalResponse", "AsymmetricDecryptRequest", "AsymmetricDecryptResponse", "AsymmetricSignRequest", @@ -234,6 +260,8 @@ def _get_version(dependency_name): "AutokeyClient", "AutokeyConfig", "Certificate", + "Challenge", + "ChallengeReply", "ChecksummedData", "CreateCryptoKeyRequest", "CreateCryptoKeyVersionRequest", @@ -242,6 +270,10 @@ def _get_version(dependency_name): "CreateKeyHandleMetadata", "CreateKeyHandleRequest", "CreateKeyRingRequest", + "CreateSingleTenantHsmInstanceMetadata", + "CreateSingleTenantHsmInstanceProposalMetadata", + "CreateSingleTenantHsmInstanceProposalRequest", + "CreateSingleTenantHsmInstanceRequest", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", @@ -249,6 +281,7 @@ def _get_version(dependency_name): "DecapsulateResponse", "DecryptRequest", "DecryptResponse", + "DeleteSingleTenantHsmInstanceProposalRequest", "DestroyCryptoKeyVersionRequest", "Digest", "EkmConfig", @@ -256,6 +289,9 @@ def _get_version(dependency_name): "EkmServiceClient", "EncryptRequest", "EncryptResponse", + "ExecuteSingleTenantHsmInstanceProposalMetadata", + "ExecuteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalResponse", "ExternalProtectionLevelOptions", "GenerateRandomBytesRequest", "GenerateRandomBytesResponse", @@ -268,6 +304,9 @@ def _get_version(dependency_name): "GetKeyHandleRequest", "GetKeyRingRequest", "GetPublicKeyRequest", + "GetSingleTenantHsmInstanceProposalRequest", + "GetSingleTenantHsmInstanceRequest", + "HsmManagementClient", "ImportCryptoKeyVersionRequest", "ImportJob", "KeyAccessJustificationsPolicy", @@ -287,6 +326,10 @@ def _get_version(dependency_name): "ListKeyHandlesResponse", "ListKeyRingsRequest", "ListKeyRingsResponse", + "ListSingleTenantHsmInstanceProposalsRequest", + "ListSingleTenantHsmInstanceProposalsResponse", + "ListSingleTenantHsmInstancesRequest", + "ListSingleTenantHsmInstancesResponse", "LocationMetadata", "MacSignRequest", "MacSignResponse", @@ -301,6 +344,8 @@ def _get_version(dependency_name): "RestoreCryptoKeyVersionRequest", "ShowEffectiveAutokeyConfigRequest", "ShowEffectiveAutokeyConfigResponse", + "SingleTenantHsmInstance", + "SingleTenantHsmInstanceProposal", "UpdateAutokeyConfigRequest", "UpdateCryptoKeyPrimaryVersionRequest", "UpdateCryptoKeyRequest", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json index b0b09eafd109..2de614e2691f 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json @@ -257,6 +257,160 @@ } } }, + "HsmManagement": { + "clients": { + "grpc": { + "libraryClient": "HsmManagementClient", + "rpcs": { + "ApproveSingleTenantHsmInstanceProposal": { + "methods": [ + "approve_single_tenant_hsm_instance_proposal" + ] + }, + "CreateSingleTenantHsmInstance": { + "methods": [ + "create_single_tenant_hsm_instance" + ] + }, + "CreateSingleTenantHsmInstanceProposal": { + "methods": [ + "create_single_tenant_hsm_instance_proposal" + ] + }, + "DeleteSingleTenantHsmInstanceProposal": { + "methods": [ + "delete_single_tenant_hsm_instance_proposal" + ] + }, + "ExecuteSingleTenantHsmInstanceProposal": { + "methods": [ + "execute_single_tenant_hsm_instance_proposal" + ] + }, + "GetSingleTenantHsmInstance": { + "methods": [ + "get_single_tenant_hsm_instance" + ] + }, + "GetSingleTenantHsmInstanceProposal": { + "methods": [ + "get_single_tenant_hsm_instance_proposal" + ] + }, + "ListSingleTenantHsmInstanceProposals": { + "methods": [ + "list_single_tenant_hsm_instance_proposals" + ] + }, + "ListSingleTenantHsmInstances": { + "methods": [ + "list_single_tenant_hsm_instances" + ] + } + } + }, + "grpc-async": { + "libraryClient": "HsmManagementAsyncClient", + "rpcs": { + "ApproveSingleTenantHsmInstanceProposal": { + "methods": [ + "approve_single_tenant_hsm_instance_proposal" + ] + }, + "CreateSingleTenantHsmInstance": { + "methods": [ + "create_single_tenant_hsm_instance" + ] + }, + "CreateSingleTenantHsmInstanceProposal": { + "methods": [ + "create_single_tenant_hsm_instance_proposal" + ] + }, + "DeleteSingleTenantHsmInstanceProposal": { + "methods": [ + "delete_single_tenant_hsm_instance_proposal" + ] + }, + "ExecuteSingleTenantHsmInstanceProposal": { + "methods": [ + "execute_single_tenant_hsm_instance_proposal" + ] + }, + "GetSingleTenantHsmInstance": { + "methods": [ + "get_single_tenant_hsm_instance" + ] + }, + "GetSingleTenantHsmInstanceProposal": { + "methods": [ + "get_single_tenant_hsm_instance_proposal" + ] + }, + "ListSingleTenantHsmInstanceProposals": { + "methods": [ + "list_single_tenant_hsm_instance_proposals" + ] + }, + "ListSingleTenantHsmInstances": { + "methods": [ + "list_single_tenant_hsm_instances" + ] + } + } + }, + "rest": { + "libraryClient": "HsmManagementClient", + "rpcs": { + "ApproveSingleTenantHsmInstanceProposal": { + "methods": [ + "approve_single_tenant_hsm_instance_proposal" + ] + }, + "CreateSingleTenantHsmInstance": { + "methods": [ + "create_single_tenant_hsm_instance" + ] + }, + "CreateSingleTenantHsmInstanceProposal": { + "methods": [ + "create_single_tenant_hsm_instance_proposal" + ] + }, + "DeleteSingleTenantHsmInstanceProposal": { + "methods": [ + "delete_single_tenant_hsm_instance_proposal" + ] + }, + "ExecuteSingleTenantHsmInstanceProposal": { + "methods": [ + "execute_single_tenant_hsm_instance_proposal" + ] + }, + "GetSingleTenantHsmInstance": { + "methods": [ + "get_single_tenant_hsm_instance" + ] + }, + "GetSingleTenantHsmInstanceProposal": { + "methods": [ + "get_single_tenant_hsm_instance_proposal" + ] + }, + "ListSingleTenantHsmInstanceProposals": { + "methods": [ + "list_single_tenant_hsm_instance_proposals" + ] + }, + "ListSingleTenantHsmInstances": { + "methods": [ + "list_single_tenant_hsm_instances" + ] + } + } + } + } + }, "KeyManagementService": { "clients": { "grpc": { diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/__init__.py new file mode 100644 index 000000000000..55269a3294b7 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import HsmManagementAsyncClient +from .client import HsmManagementClient + +__all__ = ( + "HsmManagementClient", + "HsmManagementAsyncClient", +) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/async_client.py new file mode 100644 index 000000000000..d3bf94dc949e --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/async_client.py @@ -0,0 +1,2056 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.kms_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.kms_v1.services.hsm_management import pagers +from google.cloud.kms_v1.types import hsm_management + +from .client import HsmManagementClient +from .transports.base import DEFAULT_CLIENT_INFO, HsmManagementTransport +from .transports.grpc_asyncio import HsmManagementGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class HsmManagementAsyncClient: + """Google Cloud HSM Management Service + + Provides interfaces for managing HSM instances. + + Implements a REST model with the following objects: + + - [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + - [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + """ + + _client: HsmManagementClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = HsmManagementClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = HsmManagementClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = HsmManagementClient._DEFAULT_UNIVERSE + + single_tenant_hsm_instance_path = staticmethod( + HsmManagementClient.single_tenant_hsm_instance_path + ) + parse_single_tenant_hsm_instance_path = staticmethod( + HsmManagementClient.parse_single_tenant_hsm_instance_path + ) + single_tenant_hsm_instance_proposal_path = staticmethod( + HsmManagementClient.single_tenant_hsm_instance_proposal_path + ) + parse_single_tenant_hsm_instance_proposal_path = staticmethod( + HsmManagementClient.parse_single_tenant_hsm_instance_proposal_path + ) + common_billing_account_path = staticmethod( + HsmManagementClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + HsmManagementClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(HsmManagementClient.common_folder_path) + parse_common_folder_path = staticmethod( + HsmManagementClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + HsmManagementClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + HsmManagementClient.parse_common_organization_path + ) + common_project_path = staticmethod(HsmManagementClient.common_project_path) + parse_common_project_path = staticmethod( + HsmManagementClient.parse_common_project_path + ) + common_location_path = staticmethod(HsmManagementClient.common_location_path) + parse_common_location_path = staticmethod( + HsmManagementClient.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: + HsmManagementAsyncClient: The constructed client. + """ + return HsmManagementClient.from_service_account_info.__func__(HsmManagementAsyncClient, 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: + HsmManagementAsyncClient: The constructed client. + """ + return HsmManagementClient.from_service_account_file.__func__(HsmManagementAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return HsmManagementClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> HsmManagementTransport: + """Returns the transport used by the client instance. + + Returns: + HsmManagementTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = HsmManagementClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, HsmManagementTransport, Callable[..., HsmManagementTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the hsm management async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,HsmManagementTransport,Callable[..., HsmManagementTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HsmManagementTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = HsmManagementClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.kms_v1.HsmManagementAsyncClient`.", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.kms.v1.HsmManagement", + "credentialsType": None, + }, + ) + + async def list_single_tenant_hsm_instances( + self, + request: Optional[ + Union[hsm_management.ListSingleTenantHsmInstancesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSingleTenantHsmInstancesAsyncPager: + r"""Lists + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_single_tenant_hsm_instances(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest, dict]]): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + to list, in the 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstancesAsyncPager: + Response message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.ListSingleTenantHsmInstancesRequest): + request = hsm_management.ListSingleTenantHsmInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_single_tenant_hsm_instances + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSingleTenantHsmInstancesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_single_tenant_hsm_instance( + self, + request: Optional[ + Union[hsm_management.GetSingleTenantHsmInstanceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstance: + r"""Returns metadata for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_single_tenant_hsm_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetSingleTenantHsmInstanceRequest, dict]]): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] + of the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.SingleTenantHsmInstance: + A [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be + used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using + keys created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.GetSingleTenantHsmInstanceRequest): + request = hsm_management.GetSingleTenantHsmInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_single_tenant_hsm_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_single_tenant_hsm_instance( + self, + request: Optional[ + Union[hsm_management.CreateSingleTenantHsmInstanceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + single_tenant_hsm_instance: Optional[ + hsm_management.SingleTenantHsmInstance + ] = None, + single_tenant_hsm_instance_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in a given Project and Location. User must create a + RegisterTwoFactorAuthKeys proposal with this single-tenant HSM + instance to finish setup of the instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + single_tenant_hsm_instance = kms_v1.SingleTenantHsmInstance() + single_tenant_hsm_instance.quorum_auth.total_approver_count = 2170 + + request = kms_v1.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceRequest, dict]]): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance], + in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance (:class:`google.cloud.kms_v1.types.SingleTenantHsmInstance`): + Required. An + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + with initial field values. + + This corresponds to the ``single_tenant_hsm_instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_id (:class:`str`): + Optional. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``single_tenant_hsm_instance_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.kms_v1.types.SingleTenantHsmInstance` A [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be + used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using + keys created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + single_tenant_hsm_instance, + single_tenant_hsm_instance_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.CreateSingleTenantHsmInstanceRequest): + request = hsm_management.CreateSingleTenantHsmInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if single_tenant_hsm_instance is not None: + request.single_tenant_hsm_instance = single_tenant_hsm_instance + if single_tenant_hsm_instance_id is not None: + request.single_tenant_hsm_instance_id = single_tenant_hsm_instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_single_tenant_hsm_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + hsm_management.SingleTenantHsmInstance, + metadata_type=hsm_management.CreateSingleTenantHsmInstanceMetadata, + ) + + # Done; return the response. + return response + + async def create_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.CreateSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + single_tenant_hsm_instance_proposal: Optional[ + hsm_management.SingleTenantHsmInstanceProposal + ] = None, + single_tenant_hsm_instance_proposal_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + single_tenant_hsm_instance_proposal = kms_v1.SingleTenantHsmInstanceProposal() + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.required_approver_count = 2487 + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.two_factor_public_key_pems = ['two_factor_public_key_pems_value1', 'two_factor_public_key_pems_value2'] + + request = kms_v1.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal=single_tenant_hsm_instance_proposal, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceProposalRequest, dict]]): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal]. + parent (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] + of the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_proposal (:class:`google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal`): + Required. The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to create. + + This corresponds to the ``single_tenant_hsm_instance_proposal`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_proposal_id (:class:`str`): + Optional. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``single_tenant_hsm_instance_proposal_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.kms_v1.types.SingleTenantHsmInstanceProposal` A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + single_tenant_hsm_instance_proposal, + single_tenant_hsm_instance_proposal_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.CreateSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if single_tenant_hsm_instance_proposal is not None: + request.single_tenant_hsm_instance_proposal = ( + single_tenant_hsm_instance_proposal + ) + if single_tenant_hsm_instance_proposal_id is not None: + request.single_tenant_hsm_instance_proposal_id = ( + single_tenant_hsm_instance_proposal_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + hsm_management.SingleTenantHsmInstanceProposal, + metadata_type=hsm_management.CreateSingleTenantHsmInstanceProposalMetadata, + ) + + # Done; return the response. + return response + + async def approve_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + quorum_reply: Optional[ + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.ApproveSingleTenantHsmInstanceProposalResponse: + r"""Approves a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [PENDING][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.PENDING] + state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_approve_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + quorum_reply = kms_v1.QuorumReply() + quorum_reply.challenge_replies.signed_challenge = b'signed_challenge_blob' + quorum_reply.challenge_replies.public_key_pem = "public_key_pem_value" + + request = kms_v1.ApproveSingleTenantHsmInstanceProposalRequest( + quorum_reply=quorum_reply, + name="name_value", + ) + + # Make the request + response = await client.approve_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest, dict]]): + The request object. Request message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to approve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + quorum_reply (:class:`google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply`): + Required. The reply to + [QuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.QuorumParameters] + for approving the proposal. + + This corresponds to the ``quorum_reply`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalResponse: + Response message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, quorum_reply] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ApproveSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if quorum_reply is not None: + request.quorum_reply = quorum_reply + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.approve_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def execute_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Executes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [APPROVED][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.APPROVED] + state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_execute_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + operation = client.execute_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalRequest, dict]]): + The request object. Request message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to execute. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalResponse` Response message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.execute_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + hsm_management.ExecuteSingleTenantHsmInstanceProposalResponse, + metadata_type=hsm_management.ExecuteSingleTenantHsmInstanceProposalMetadata, + ) + + # Done; return the response. + return response + + async def get_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.GetSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstanceProposal: + r"""Returns metadata for a given + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + response = await client.get_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetSingleTenantHsmInstanceProposalRequest, dict]]): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal: + A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.GetSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_single_tenant_hsm_instance_proposals( + self, + request: Optional[ + Union[hsm_management.ListSingleTenantHsmInstanceProposalsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSingleTenantHsmInstanceProposalsAsyncPager: + r"""Lists + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_single_tenant_hsm_instance_proposals(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instance_proposals(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest, dict]]): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + parent (:class:`str`): + Required. The resource name of the single tenant HSM + instance associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to list, in the format + ``projects/*/locations/*/singleTenantHsmInstances/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstanceProposalsAsyncPager: + Response message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ListSingleTenantHsmInstanceProposalsRequest + ): + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_single_tenant_hsm_instance_proposals + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListSingleTenantHsmInstanceProposalsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_delete_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + await client.delete_single_tenant_hsm_instance_proposal(request=request) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.DeleteSingleTenantHsmInstanceProposalRequest, dict]]): + The request object. Request message for + [HsmManagement.DeleteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.DeleteSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "HsmManagementAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("HsmManagementAsyncClient",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/client.py new file mode 100644 index 000000000000..6bdbc7b018ce --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/client.py @@ -0,0 +1,2528 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.kms_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.kms_v1.services.hsm_management import pagers +from google.cloud.kms_v1.types import hsm_management + +from .transports.base import DEFAULT_CLIENT_INFO, HsmManagementTransport +from .transports.grpc import HsmManagementGrpcTransport +from .transports.grpc_asyncio import HsmManagementGrpcAsyncIOTransport +from .transports.rest import HsmManagementRestTransport + + +class HsmManagementClientMeta(type): + """Metaclass for the HsmManagement 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[HsmManagementTransport]] + _transport_registry["grpc"] = HsmManagementGrpcTransport + _transport_registry["grpc_asyncio"] = HsmManagementGrpcAsyncIOTransport + _transport_registry["rest"] = HsmManagementRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[HsmManagementTransport]: + """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 HsmManagementClient(metaclass=HsmManagementClientMeta): + """Google Cloud HSM Management Service + + Provides interfaces for managing HSM instances. + + Implements a REST model with the following objects: + + - [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + - [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + HsmManagementClient: 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: + HsmManagementClient: 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) -> HsmManagementTransport: + """Returns the transport used by the client instance. + + Returns: + HsmManagementTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def single_tenant_hsm_instance_path( + project: str, + location: str, + single_tenant_hsm_instance: str, + ) -> str: + """Returns a fully-qualified single_tenant_hsm_instance string.""" + return "projects/{project}/locations/{location}/singleTenantHsmInstances/{single_tenant_hsm_instance}".format( + project=project, + location=location, + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + + @staticmethod + def parse_single_tenant_hsm_instance_path(path: str) -> Dict[str, str]: + """Parses a single_tenant_hsm_instance path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/singleTenantHsmInstances/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def single_tenant_hsm_instance_proposal_path( + project: str, + location: str, + single_tenant_hsm_instance: str, + proposal: str, + ) -> str: + """Returns a fully-qualified single_tenant_hsm_instance_proposal string.""" + return "projects/{project}/locations/{location}/singleTenantHsmInstances/{single_tenant_hsm_instance}/proposals/{proposal}".format( + project=project, + location=location, + single_tenant_hsm_instance=single_tenant_hsm_instance, + proposal=proposal, + ) + + @staticmethod + def parse_single_tenant_hsm_instance_proposal_path(path: str) -> Dict[str, str]: + """Parses a single_tenant_hsm_instance_proposal path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/singleTenantHsmInstances/(?P.+?)/proposals/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = HsmManagementClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = HsmManagementClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = HsmManagementClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = HsmManagementClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = HsmManagementClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, HsmManagementTransport, Callable[..., HsmManagementTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the hsm management client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,HsmManagementTransport,Callable[..., HsmManagementTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HsmManagementTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = HsmManagementClient._read_environment_variables() + self._client_cert_source = HsmManagementClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = HsmManagementClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, HsmManagementTransport) + if transport_provided: + # transport is a HsmManagementTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(HsmManagementTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or HsmManagementClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[HsmManagementTransport], Callable[..., HsmManagementTransport] + ] = ( + HsmManagementClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HsmManagementTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.kms_v1.HsmManagementClient`.", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.kms.v1.HsmManagement", + "credentialsType": None, + }, + ) + + def list_single_tenant_hsm_instances( + self, + request: Optional[ + Union[hsm_management.ListSingleTenantHsmInstancesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSingleTenantHsmInstancesPager: + r"""Lists + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_single_tenant_hsm_instances(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest, dict]): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + parent (str): + Required. The resource name of the location associated + with the + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + to list, in the 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstancesPager: + Response message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.ListSingleTenantHsmInstancesRequest): + request = hsm_management.ListSingleTenantHsmInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_single_tenant_hsm_instances + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSingleTenantHsmInstancesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_single_tenant_hsm_instance( + self, + request: Optional[ + Union[hsm_management.GetSingleTenantHsmInstanceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstance: + r"""Returns metadata for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_single_tenant_hsm_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetSingleTenantHsmInstanceRequest, dict]): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance]. + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] + of the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.SingleTenantHsmInstance: + A [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be + used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using + keys created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.GetSingleTenantHsmInstanceRequest): + request = hsm_management.GetSingleTenantHsmInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_single_tenant_hsm_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_single_tenant_hsm_instance( + self, + request: Optional[ + Union[hsm_management.CreateSingleTenantHsmInstanceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + single_tenant_hsm_instance: Optional[ + hsm_management.SingleTenantHsmInstance + ] = None, + single_tenant_hsm_instance_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in a given Project and Location. User must create a + RegisterTwoFactorAuthKeys proposal with this single-tenant HSM + instance to finish setup of the instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + single_tenant_hsm_instance = kms_v1.SingleTenantHsmInstance() + single_tenant_hsm_instance.quorum_auth.total_approver_count = 2170 + + request = kms_v1.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceRequest, dict]): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance]. + parent (str): + Required. The resource name of the location associated + with the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance], + in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstance): + Required. An + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + with initial field values. + + This corresponds to the ``single_tenant_hsm_instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_id (str): + Optional. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``single_tenant_hsm_instance_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.kms_v1.types.SingleTenantHsmInstance` A [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be + used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using + keys created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + single_tenant_hsm_instance, + single_tenant_hsm_instance_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hsm_management.CreateSingleTenantHsmInstanceRequest): + request = hsm_management.CreateSingleTenantHsmInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if single_tenant_hsm_instance is not None: + request.single_tenant_hsm_instance = single_tenant_hsm_instance + if single_tenant_hsm_instance_id is not None: + request.single_tenant_hsm_instance_id = single_tenant_hsm_instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_single_tenant_hsm_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + hsm_management.SingleTenantHsmInstance, + metadata_type=hsm_management.CreateSingleTenantHsmInstanceMetadata, + ) + + # Done; return the response. + return response + + def create_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.CreateSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + single_tenant_hsm_instance_proposal: Optional[ + hsm_management.SingleTenantHsmInstanceProposal + ] = None, + single_tenant_hsm_instance_proposal_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + single_tenant_hsm_instance_proposal = kms_v1.SingleTenantHsmInstanceProposal() + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.required_approver_count = 2487 + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.two_factor_public_key_pems = ['two_factor_public_key_pems_value1', 'two_factor_public_key_pems_value2'] + + request = kms_v1.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal=single_tenant_hsm_instance_proposal, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceProposalRequest, dict]): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal]. + parent (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] + of the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_proposal (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal): + Required. The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to create. + + This corresponds to the ``single_tenant_hsm_instance_proposal`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + single_tenant_hsm_instance_proposal_id (str): + Optional. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``single_tenant_hsm_instance_proposal_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal` A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + single_tenant_hsm_instance_proposal, + single_tenant_hsm_instance_proposal_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.CreateSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if single_tenant_hsm_instance_proposal is not None: + request.single_tenant_hsm_instance_proposal = ( + single_tenant_hsm_instance_proposal + ) + if single_tenant_hsm_instance_proposal_id is not None: + request.single_tenant_hsm_instance_proposal_id = ( + single_tenant_hsm_instance_proposal_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + hsm_management.SingleTenantHsmInstanceProposal, + metadata_type=hsm_management.CreateSingleTenantHsmInstanceProposalMetadata, + ) + + # Done; return the response. + return response + + def approve_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + quorum_reply: Optional[ + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.ApproveSingleTenantHsmInstanceProposalResponse: + r"""Approves a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [PENDING][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.PENDING] + state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_approve_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + quorum_reply = kms_v1.QuorumReply() + quorum_reply.challenge_replies.signed_challenge = b'signed_challenge_blob' + quorum_reply.challenge_replies.public_key_pem = "public_key_pem_value" + + request = kms_v1.ApproveSingleTenantHsmInstanceProposalRequest( + quorum_reply=quorum_reply, + name="name_value", + ) + + # Make the request + response = client.approve_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest, dict]): + The request object. Request message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to approve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + quorum_reply (google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply): + Required. The reply to + [QuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.QuorumParameters] + for approving the proposal. + + This corresponds to the ``quorum_reply`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalResponse: + Response message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, quorum_reply] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ApproveSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if quorum_reply is not None: + request.quorum_reply = quorum_reply + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.approve_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def execute_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Executes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [APPROVED][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.APPROVED] + state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_execute_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + operation = client.execute_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalRequest, dict]): + The request object. Request message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to execute. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalResponse` Response message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.execute_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + hsm_management.ExecuteSingleTenantHsmInstanceProposalResponse, + metadata_type=hsm_management.ExecuteSingleTenantHsmInstanceProposalMetadata, + ) + + # Done; return the response. + return response + + def get_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.GetSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstanceProposal: + r"""Returns metadata for a given + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + response = client.get_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetSingleTenantHsmInstanceProposalRequest, dict]): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal]. + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal: + A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.GetSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_single_tenant_hsm_instance_proposals( + self, + request: Optional[ + Union[hsm_management.ListSingleTenantHsmInstanceProposalsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSingleTenantHsmInstanceProposalsPager: + r"""Lists + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_single_tenant_hsm_instance_proposals(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instance_proposals(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest, dict]): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + parent (str): + Required. The resource name of the single tenant HSM + instance associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to list, in the format + ``projects/*/locations/*/singleTenantHsmInstances/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstanceProposalsPager: + Response message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.ListSingleTenantHsmInstanceProposalsRequest + ): + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_single_tenant_hsm_instance_proposals + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListSingleTenantHsmInstanceProposalsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_single_tenant_hsm_instance_proposal( + self, + request: Optional[ + Union[hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_delete_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + client.delete_single_tenant_hsm_instance_proposal(request=request) + + Args: + request (Union[google.cloud.kms_v1.types.DeleteSingleTenantHsmInstanceProposalRequest, dict]): + The request object. Request message for + [HsmManagement.DeleteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal]. + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, hsm_management.DeleteSingleTenantHsmInstanceProposalRequest + ): + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_single_tenant_hsm_instance_proposal + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "HsmManagementClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("HsmManagementClient",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/pagers.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/pagers.py new file mode 100644 index 000000000000..8ddb79e3b47e --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/pagers.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.types import hsm_management + + +class ListSingleTenantHsmInstancesPager: + """A pager for iterating through ``list_single_tenant_hsm_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``single_tenant_hsm_instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSingleTenantHsmInstances`` requests and continue to iterate + through the ``single_tenant_hsm_instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., hsm_management.ListSingleTenantHsmInstancesResponse], + request: hsm_management.ListSingleTenantHsmInstancesRequest, + response: hsm_management.ListSingleTenantHsmInstancesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hsm_management.ListSingleTenantHsmInstancesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hsm_management.ListSingleTenantHsmInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[hsm_management.SingleTenantHsmInstance]: + for page in self.pages: + yield from page.single_tenant_hsm_instances + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSingleTenantHsmInstancesAsyncPager: + """A pager for iterating through ``list_single_tenant_hsm_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``single_tenant_hsm_instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSingleTenantHsmInstances`` requests and continue to iterate + through the ``single_tenant_hsm_instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse` + attributes are available on the 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[hsm_management.ListSingleTenantHsmInstancesResponse] + ], + request: hsm_management.ListSingleTenantHsmInstancesRequest, + response: hsm_management.ListSingleTenantHsmInstancesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListSingleTenantHsmInstancesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hsm_management.ListSingleTenantHsmInstancesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[hsm_management.ListSingleTenantHsmInstancesResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[hsm_management.SingleTenantHsmInstance]: + async def async_generator(): + async for page in self.pages: + for response in page.single_tenant_hsm_instances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSingleTenantHsmInstanceProposalsPager: + """A pager for iterating through ``list_single_tenant_hsm_instance_proposals`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``single_tenant_hsm_instance_proposals`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSingleTenantHsmInstanceProposals`` requests and continue to iterate + through the ``single_tenant_hsm_instance_proposals`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., hsm_management.ListSingleTenantHsmInstanceProposalsResponse + ], + request: hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + response: hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[hsm_management.ListSingleTenantHsmInstanceProposalsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[hsm_management.SingleTenantHsmInstanceProposal]: + for page in self.pages: + yield from page.single_tenant_hsm_instance_proposals + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSingleTenantHsmInstanceProposalsAsyncPager: + """A pager for iterating through ``list_single_tenant_hsm_instance_proposals`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``single_tenant_hsm_instance_proposals`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSingleTenantHsmInstanceProposals`` requests and continue to iterate + through the ``single_tenant_hsm_instance_proposals`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse` + attributes are available on the 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[hsm_management.ListSingleTenantHsmInstanceProposalsResponse] + ], + request: hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + response: hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[hsm_management.ListSingleTenantHsmInstanceProposalsResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[hsm_management.SingleTenantHsmInstanceProposal]: + async def async_generator(): + async for page in self.pages: + for response in page.single_tenant_hsm_instance_proposals: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/README.rst b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/README.rst new file mode 100644 index 000000000000..e999469435d7 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`HsmManagementTransport` is the ABC for all transports. +- public child `HsmManagementGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `HsmManagementGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseHsmManagementRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `HsmManagementRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/__init__.py new file mode 100644 index 000000000000..826d85dcaef5 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 HsmManagementTransport +from .grpc import HsmManagementGrpcTransport +from .grpc_asyncio import HsmManagementGrpcAsyncIOTransport +from .rest import HsmManagementRestInterceptor, HsmManagementRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HsmManagementTransport]] +_transport_registry["grpc"] = HsmManagementGrpcTransport +_transport_registry["grpc_asyncio"] = HsmManagementGrpcAsyncIOTransport +_transport_registry["rest"] = HsmManagementRestTransport + +__all__ = ( + "HsmManagementTransport", + "HsmManagementGrpcTransport", + "HsmManagementGrpcAsyncIOTransport", + "HsmManagementRestTransport", + "HsmManagementRestInterceptor", +) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/base.py new file mode 100644 index 000000000000..50b2fde3af0a --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/base.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.kms_v1 import gapic_version as package_version +from google.cloud.kms_v1.types import hsm_management + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class HsmManagementTransport(abc.ABC): + """Abstract transport class for HsmManagement.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ) + + DEFAULT_HOST: str = "cloudkms.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_single_tenant_hsm_instances: gapic_v1.method.wrap_method( + self.list_single_tenant_hsm_instances, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_single_tenant_hsm_instance: gapic_v1.method.wrap_method( + self.get_single_tenant_hsm_instance, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_single_tenant_hsm_instance: gapic_v1.method.wrap_method( + self.create_single_tenant_hsm_instance, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_single_tenant_hsm_instance_proposal: gapic_v1.method.wrap_method( + self.create_single_tenant_hsm_instance_proposal, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.approve_single_tenant_hsm_instance_proposal: gapic_v1.method.wrap_method( + self.approve_single_tenant_hsm_instance_proposal, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.execute_single_tenant_hsm_instance_proposal: gapic_v1.method.wrap_method( + self.execute_single_tenant_hsm_instance_proposal, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_single_tenant_hsm_instance_proposal: gapic_v1.method.wrap_method( + self.get_single_tenant_hsm_instance_proposal, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_single_tenant_hsm_instance_proposals: gapic_v1.method.wrap_method( + self.list_single_tenant_hsm_instance_proposals, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_single_tenant_hsm_instance_proposal: gapic_v1.method.wrap_method( + self.delete_single_tenant_hsm_instance_proposal, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_single_tenant_hsm_instances( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstancesRequest], + Union[ + hsm_management.ListSingleTenantHsmInstancesResponse, + Awaitable[hsm_management.ListSingleTenantHsmInstancesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceRequest], + Union[ + hsm_management.SingleTenantHsmInstance, + Awaitable[hsm_management.SingleTenantHsmInstance], + ], + ]: + raise NotImplementedError() + + @property + def create_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceProposalRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def approve_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ApproveSingleTenantHsmInstanceProposalRequest], + Union[ + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse, + Awaitable[hsm_management.ApproveSingleTenantHsmInstanceProposalResponse], + ], + ]: + raise NotImplementedError() + + @property + def execute_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceProposalRequest], + Union[ + hsm_management.SingleTenantHsmInstanceProposal, + Awaitable[hsm_management.SingleTenantHsmInstanceProposal], + ], + ]: + raise NotImplementedError() + + @property + def list_single_tenant_hsm_instance_proposals( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstanceProposalsRequest], + Union[ + hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + Awaitable[hsm_management.ListSingleTenantHsmInstanceProposalsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.DeleteSingleTenantHsmInstanceProposalRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("HsmManagementTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc.py new file mode 100644 index 000000000000..b312dbccb779 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc.py @@ -0,0 +1,803 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.kms_v1.types import hsm_management + +from .base import DEFAULT_CLIENT_INFO, HsmManagementTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HsmManagementGrpcTransport(HsmManagementTransport): + """gRPC backend transport for HsmManagement. + + Google Cloud HSM Management Service + + Provides interfaces for managing HSM instances. + + Implements a REST model with the following objects: + + - [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + - [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudkms.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudkms.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_single_tenant_hsm_instances( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstancesRequest], + hsm_management.ListSingleTenantHsmInstancesResponse, + ]: + r"""Return a callable for the list single tenant hsm + instances method over gRPC. + + Lists + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.ListSingleTenantHsmInstancesRequest], + ~.ListSingleTenantHsmInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_single_tenant_hsm_instances" not in self._stubs: + self._stubs[ + "list_single_tenant_hsm_instances" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ListSingleTenantHsmInstances", + request_serializer=hsm_management.ListSingleTenantHsmInstancesRequest.serialize, + response_deserializer=hsm_management.ListSingleTenantHsmInstancesResponse.deserialize, + ) + return self._stubs["list_single_tenant_hsm_instances"] + + @property + def get_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceRequest], + hsm_management.SingleTenantHsmInstance, + ]: + r"""Return a callable for the get single tenant hsm instance method over gRPC. + + Returns metadata for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.GetSingleTenantHsmInstanceRequest], + ~.SingleTenantHsmInstance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_single_tenant_hsm_instance" not in self._stubs: + self._stubs[ + "get_single_tenant_hsm_instance" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/GetSingleTenantHsmInstance", + request_serializer=hsm_management.GetSingleTenantHsmInstanceRequest.serialize, + response_deserializer=hsm_management.SingleTenantHsmInstance.deserialize, + ) + return self._stubs["get_single_tenant_hsm_instance"] + + @property + def create_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create single tenant hsm + instance method over gRPC. + + Creates a new + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in a given Project and Location. User must create a + RegisterTwoFactorAuthKeys proposal with this single-tenant HSM + instance to finish setup of the instance. + + Returns: + Callable[[~.CreateSingleTenantHsmInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_single_tenant_hsm_instance" not in self._stubs: + self._stubs[ + "create_single_tenant_hsm_instance" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/CreateSingleTenantHsmInstance", + request_serializer=hsm_management.CreateSingleTenantHsmInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_single_tenant_hsm_instance"] + + @property + def create_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceProposalRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create single tenant hsm + instance proposal method over gRPC. + + Creates a new + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.CreateSingleTenantHsmInstanceProposalRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "create_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/CreateSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.CreateSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_single_tenant_hsm_instance_proposal"] + + @property + def approve_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ApproveSingleTenantHsmInstanceProposalRequest], + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse, + ]: + r"""Return a callable for the approve single tenant hsm + instance proposal method over gRPC. + + Approves a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [PENDING][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.PENDING] + state. + + Returns: + Callable[[~.ApproveSingleTenantHsmInstanceProposalRequest], + ~.ApproveSingleTenantHsmInstanceProposalResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "approve_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "approve_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ApproveSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.deserialize, + ) + return self._stubs["approve_single_tenant_hsm_instance_proposal"] + + @property + def execute_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the execute single tenant hsm + instance proposal method over gRPC. + + Executes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [APPROVED][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.APPROVED] + state. + + Returns: + Callable[[~.ExecuteSingleTenantHsmInstanceProposalRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "execute_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "execute_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ExecuteSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["execute_single_tenant_hsm_instance_proposal"] + + @property + def get_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceProposalRequest], + hsm_management.SingleTenantHsmInstanceProposal, + ]: + r"""Return a callable for the get single tenant hsm instance + proposal method over gRPC. + + Returns metadata for a given + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.GetSingleTenantHsmInstanceProposalRequest], + ~.SingleTenantHsmInstanceProposal]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "get_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/GetSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.GetSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=hsm_management.SingleTenantHsmInstanceProposal.deserialize, + ) + return self._stubs["get_single_tenant_hsm_instance_proposal"] + + @property + def list_single_tenant_hsm_instance_proposals( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstanceProposalsRequest], + hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + ]: + r"""Return a callable for the list single tenant hsm + instance proposals method over gRPC. + + Lists + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.ListSingleTenantHsmInstanceProposalsRequest], + ~.ListSingleTenantHsmInstanceProposalsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_single_tenant_hsm_instance_proposals" not in self._stubs: + self._stubs[ + "list_single_tenant_hsm_instance_proposals" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ListSingleTenantHsmInstanceProposals", + request_serializer=hsm_management.ListSingleTenantHsmInstanceProposalsRequest.serialize, + response_deserializer=hsm_management.ListSingleTenantHsmInstanceProposalsResponse.deserialize, + ) + return self._stubs["list_single_tenant_hsm_instance_proposals"] + + @property + def delete_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.DeleteSingleTenantHsmInstanceProposalRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete single tenant hsm + instance proposal method over gRPC. + + Deletes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.DeleteSingleTenantHsmInstanceProposalRequest], + ~.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_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "delete_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/DeleteSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.DeleteSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_single_tenant_hsm_instance_proposal"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("HsmManagementGrpcTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc_asyncio.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5bb0785931b0 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/grpc_asyncio.py @@ -0,0 +1,988 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.kms_v1.types import hsm_management + +from .base import DEFAULT_CLIENT_INFO, HsmManagementTransport +from .grpc import HsmManagementGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HsmManagementGrpcAsyncIOTransport(HsmManagementTransport): + """gRPC AsyncIO backend transport for HsmManagement. + + Google Cloud HSM Management Service + + Provides interfaces for managing HSM instances. + + Implements a REST model with the following objects: + + - [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + - [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudkms.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudkms.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_single_tenant_hsm_instances( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstancesRequest], + Awaitable[hsm_management.ListSingleTenantHsmInstancesResponse], + ]: + r"""Return a callable for the list single tenant hsm + instances method over gRPC. + + Lists + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.ListSingleTenantHsmInstancesRequest], + Awaitable[~.ListSingleTenantHsmInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_single_tenant_hsm_instances" not in self._stubs: + self._stubs[ + "list_single_tenant_hsm_instances" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ListSingleTenantHsmInstances", + request_serializer=hsm_management.ListSingleTenantHsmInstancesRequest.serialize, + response_deserializer=hsm_management.ListSingleTenantHsmInstancesResponse.deserialize, + ) + return self._stubs["list_single_tenant_hsm_instances"] + + @property + def get_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceRequest], + Awaitable[hsm_management.SingleTenantHsmInstance], + ]: + r"""Return a callable for the get single tenant hsm instance method over gRPC. + + Returns metadata for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.GetSingleTenantHsmInstanceRequest], + Awaitable[~.SingleTenantHsmInstance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_single_tenant_hsm_instance" not in self._stubs: + self._stubs[ + "get_single_tenant_hsm_instance" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/GetSingleTenantHsmInstance", + request_serializer=hsm_management.GetSingleTenantHsmInstanceRequest.serialize, + response_deserializer=hsm_management.SingleTenantHsmInstance.deserialize, + ) + return self._stubs["get_single_tenant_hsm_instance"] + + @property + def create_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create single tenant hsm + instance method over gRPC. + + Creates a new + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in a given Project and Location. User must create a + RegisterTwoFactorAuthKeys proposal with this single-tenant HSM + instance to finish setup of the instance. + + Returns: + Callable[[~.CreateSingleTenantHsmInstanceRequest], + 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_single_tenant_hsm_instance" not in self._stubs: + self._stubs[ + "create_single_tenant_hsm_instance" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/CreateSingleTenantHsmInstance", + request_serializer=hsm_management.CreateSingleTenantHsmInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_single_tenant_hsm_instance"] + + @property + def create_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceProposalRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create single tenant hsm + instance proposal method over gRPC. + + Creates a new + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Returns: + Callable[[~.CreateSingleTenantHsmInstanceProposalRequest], + 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_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "create_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/CreateSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.CreateSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_single_tenant_hsm_instance_proposal"] + + @property + def approve_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ApproveSingleTenantHsmInstanceProposalRequest], + Awaitable[hsm_management.ApproveSingleTenantHsmInstanceProposalResponse], + ]: + r"""Return a callable for the approve single tenant hsm + instance proposal method over gRPC. + + Approves a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [PENDING][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.PENDING] + state. + + Returns: + Callable[[~.ApproveSingleTenantHsmInstanceProposalRequest], + Awaitable[~.ApproveSingleTenantHsmInstanceProposalResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "approve_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "approve_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ApproveSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.deserialize, + ) + return self._stubs["approve_single_tenant_hsm_instance_proposal"] + + @property + def execute_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the execute single tenant hsm + instance proposal method over gRPC. + + Executes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + for a given + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The proposal must be in the + [APPROVED][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.State.APPROVED] + state. + + Returns: + Callable[[~.ExecuteSingleTenantHsmInstanceProposalRequest], + 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 "execute_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "execute_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ExecuteSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["execute_single_tenant_hsm_instance_proposal"] + + @property + def get_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceProposalRequest], + Awaitable[hsm_management.SingleTenantHsmInstanceProposal], + ]: + r"""Return a callable for the get single tenant hsm instance + proposal method over gRPC. + + Returns metadata for a given + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.GetSingleTenantHsmInstanceProposalRequest], + Awaitable[~.SingleTenantHsmInstanceProposal]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "get_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/GetSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.GetSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=hsm_management.SingleTenantHsmInstanceProposal.deserialize, + ) + return self._stubs["get_single_tenant_hsm_instance_proposal"] + + @property + def list_single_tenant_hsm_instance_proposals( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstanceProposalsRequest], + Awaitable[hsm_management.ListSingleTenantHsmInstanceProposalsResponse], + ]: + r"""Return a callable for the list single tenant hsm + instance proposals method over gRPC. + + Lists + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.ListSingleTenantHsmInstanceProposalsRequest], + Awaitable[~.ListSingleTenantHsmInstanceProposalsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_single_tenant_hsm_instance_proposals" not in self._stubs: + self._stubs[ + "list_single_tenant_hsm_instance_proposals" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/ListSingleTenantHsmInstanceProposals", + request_serializer=hsm_management.ListSingleTenantHsmInstanceProposalsRequest.serialize, + response_deserializer=hsm_management.ListSingleTenantHsmInstanceProposalsResponse.deserialize, + ) + return self._stubs["list_single_tenant_hsm_instance_proposals"] + + @property + def delete_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.DeleteSingleTenantHsmInstanceProposalRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete single tenant hsm + instance proposal method over gRPC. + + Deletes a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Returns: + Callable[[~.DeleteSingleTenantHsmInstanceProposalRequest], + 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_single_tenant_hsm_instance_proposal" not in self._stubs: + self._stubs[ + "delete_single_tenant_hsm_instance_proposal" + ] = self._logged_channel.unary_unary( + "/google.cloud.kms.v1.HsmManagement/DeleteSingleTenantHsmInstanceProposal", + request_serializer=hsm_management.DeleteSingleTenantHsmInstanceProposalRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_single_tenant_hsm_instance_proposal"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_single_tenant_hsm_instances: self._wrap_method( + self.list_single_tenant_hsm_instances, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_single_tenant_hsm_instance: self._wrap_method( + self.get_single_tenant_hsm_instance, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_single_tenant_hsm_instance: self._wrap_method( + self.create_single_tenant_hsm_instance, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_single_tenant_hsm_instance_proposal: self._wrap_method( + self.create_single_tenant_hsm_instance_proposal, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.approve_single_tenant_hsm_instance_proposal: self._wrap_method( + self.approve_single_tenant_hsm_instance_proposal, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.execute_single_tenant_hsm_instance_proposal: self._wrap_method( + self.execute_single_tenant_hsm_instance_proposal, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_single_tenant_hsm_instance_proposal: self._wrap_method( + self.get_single_tenant_hsm_instance_proposal, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_single_tenant_hsm_instance_proposals: self._wrap_method( + self.list_single_tenant_hsm_instance_proposals, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_single_tenant_hsm_instance_proposal: self._wrap_method( + self.delete_single_tenant_hsm_instance_proposal, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("HsmManagementGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest.py new file mode 100644 index 000000000000..77ffd16034e6 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest.py @@ -0,0 +1,3246 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.kms_v1.types import hsm_management + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseHsmManagementRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class HsmManagementRestInterceptor: + """Interceptor for HsmManagement. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the HsmManagementRestTransport. + + .. code-block:: python + class MyCustomHsmManagementInterceptor(HsmManagementRestInterceptor): + def pre_approve_single_tenant_hsm_instance_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_approve_single_tenant_hsm_instance_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_single_tenant_hsm_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_single_tenant_hsm_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_single_tenant_hsm_instance_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_single_tenant_hsm_instance_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_single_tenant_hsm_instance_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_execute_single_tenant_hsm_instance_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_single_tenant_hsm_instance_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_single_tenant_hsm_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_single_tenant_hsm_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_single_tenant_hsm_instance_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_single_tenant_hsm_instance_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_single_tenant_hsm_instance_proposals(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_single_tenant_hsm_instance_proposals(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_single_tenant_hsm_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_single_tenant_hsm_instances(self, response): + logging.log(f"Received response: {response}") + return response + + transport = HsmManagementRestTransport(interceptor=MyCustomHsmManagementInterceptor()) + client = HsmManagementClient(transport=transport) + + + """ + + def pre_approve_single_tenant_hsm_instance_proposal( + self, + request: hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for approve_single_tenant_hsm_instance_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_approve_single_tenant_hsm_instance_proposal( + self, response: hsm_management.ApproveSingleTenantHsmInstanceProposalResponse + ) -> hsm_management.ApproveSingleTenantHsmInstanceProposalResponse: + """Post-rpc interceptor for approve_single_tenant_hsm_instance_proposal + + DEPRECATED. Please use the `post_approve_single_tenant_hsm_instance_proposal_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_approve_single_tenant_hsm_instance_proposal` interceptor runs + before the `post_approve_single_tenant_hsm_instance_proposal_with_metadata` interceptor. + """ + return response + + def post_approve_single_tenant_hsm_instance_proposal_with_metadata( + self, + response: hsm_management.ApproveSingleTenantHsmInstanceProposalResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for approve_single_tenant_hsm_instance_proposal + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_approve_single_tenant_hsm_instance_proposal_with_metadata` + interceptor in new development instead of the `post_approve_single_tenant_hsm_instance_proposal` interceptor. + When both interceptors are used, this `post_approve_single_tenant_hsm_instance_proposal_with_metadata` interceptor runs after the + `post_approve_single_tenant_hsm_instance_proposal` interceptor. The (possibly modified) response returned by + `post_approve_single_tenant_hsm_instance_proposal` will be passed to + `post_approve_single_tenant_hsm_instance_proposal_with_metadata`. + """ + return response, metadata + + def pre_create_single_tenant_hsm_instance( + self, + request: hsm_management.CreateSingleTenantHsmInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.CreateSingleTenantHsmInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_single_tenant_hsm_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_create_single_tenant_hsm_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_single_tenant_hsm_instance + + DEPRECATED. Please use the `post_create_single_tenant_hsm_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_create_single_tenant_hsm_instance` interceptor runs + before the `post_create_single_tenant_hsm_instance_with_metadata` interceptor. + """ + return response + + def post_create_single_tenant_hsm_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_single_tenant_hsm_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_create_single_tenant_hsm_instance_with_metadata` + interceptor in new development instead of the `post_create_single_tenant_hsm_instance` interceptor. + When both interceptors are used, this `post_create_single_tenant_hsm_instance_with_metadata` interceptor runs after the + `post_create_single_tenant_hsm_instance` interceptor. The (possibly modified) response returned by + `post_create_single_tenant_hsm_instance` will be passed to + `post_create_single_tenant_hsm_instance_with_metadata`. + """ + return response, metadata + + def pre_create_single_tenant_hsm_instance_proposal( + self, + request: hsm_management.CreateSingleTenantHsmInstanceProposalRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.CreateSingleTenantHsmInstanceProposalRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_single_tenant_hsm_instance_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_create_single_tenant_hsm_instance_proposal( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_single_tenant_hsm_instance_proposal + + DEPRECATED. Please use the `post_create_single_tenant_hsm_instance_proposal_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_create_single_tenant_hsm_instance_proposal` interceptor runs + before the `post_create_single_tenant_hsm_instance_proposal_with_metadata` interceptor. + """ + return response + + def post_create_single_tenant_hsm_instance_proposal_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_single_tenant_hsm_instance_proposal + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_create_single_tenant_hsm_instance_proposal_with_metadata` + interceptor in new development instead of the `post_create_single_tenant_hsm_instance_proposal` interceptor. + When both interceptors are used, this `post_create_single_tenant_hsm_instance_proposal_with_metadata` interceptor runs after the + `post_create_single_tenant_hsm_instance_proposal` interceptor. The (possibly modified) response returned by + `post_create_single_tenant_hsm_instance_proposal` will be passed to + `post_create_single_tenant_hsm_instance_proposal_with_metadata`. + """ + return response, metadata + + def pre_delete_single_tenant_hsm_instance_proposal( + self, + request: hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_single_tenant_hsm_instance_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def pre_execute_single_tenant_hsm_instance_proposal( + self, + request: hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for execute_single_tenant_hsm_instance_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_execute_single_tenant_hsm_instance_proposal( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for execute_single_tenant_hsm_instance_proposal + + DEPRECATED. Please use the `post_execute_single_tenant_hsm_instance_proposal_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_execute_single_tenant_hsm_instance_proposal` interceptor runs + before the `post_execute_single_tenant_hsm_instance_proposal_with_metadata` interceptor. + """ + return response + + def post_execute_single_tenant_hsm_instance_proposal_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for execute_single_tenant_hsm_instance_proposal + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_execute_single_tenant_hsm_instance_proposal_with_metadata` + interceptor in new development instead of the `post_execute_single_tenant_hsm_instance_proposal` interceptor. + When both interceptors are used, this `post_execute_single_tenant_hsm_instance_proposal_with_metadata` interceptor runs after the + `post_execute_single_tenant_hsm_instance_proposal` interceptor. The (possibly modified) response returned by + `post_execute_single_tenant_hsm_instance_proposal` will be passed to + `post_execute_single_tenant_hsm_instance_proposal_with_metadata`. + """ + return response, metadata + + def pre_get_single_tenant_hsm_instance( + self, + request: hsm_management.GetSingleTenantHsmInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.GetSingleTenantHsmInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_single_tenant_hsm_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_get_single_tenant_hsm_instance( + self, response: hsm_management.SingleTenantHsmInstance + ) -> hsm_management.SingleTenantHsmInstance: + """Post-rpc interceptor for get_single_tenant_hsm_instance + + DEPRECATED. Please use the `post_get_single_tenant_hsm_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_get_single_tenant_hsm_instance` interceptor runs + before the `post_get_single_tenant_hsm_instance_with_metadata` interceptor. + """ + return response + + def post_get_single_tenant_hsm_instance_with_metadata( + self, + response: hsm_management.SingleTenantHsmInstance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.SingleTenantHsmInstance, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_single_tenant_hsm_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_get_single_tenant_hsm_instance_with_metadata` + interceptor in new development instead of the `post_get_single_tenant_hsm_instance` interceptor. + When both interceptors are used, this `post_get_single_tenant_hsm_instance_with_metadata` interceptor runs after the + `post_get_single_tenant_hsm_instance` interceptor. The (possibly modified) response returned by + `post_get_single_tenant_hsm_instance` will be passed to + `post_get_single_tenant_hsm_instance_with_metadata`. + """ + return response, metadata + + def pre_get_single_tenant_hsm_instance_proposal( + self, + request: hsm_management.GetSingleTenantHsmInstanceProposalRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.GetSingleTenantHsmInstanceProposalRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_single_tenant_hsm_instance_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_get_single_tenant_hsm_instance_proposal( + self, response: hsm_management.SingleTenantHsmInstanceProposal + ) -> hsm_management.SingleTenantHsmInstanceProposal: + """Post-rpc interceptor for get_single_tenant_hsm_instance_proposal + + DEPRECATED. Please use the `post_get_single_tenant_hsm_instance_proposal_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_get_single_tenant_hsm_instance_proposal` interceptor runs + before the `post_get_single_tenant_hsm_instance_proposal_with_metadata` interceptor. + """ + return response + + def post_get_single_tenant_hsm_instance_proposal_with_metadata( + self, + response: hsm_management.SingleTenantHsmInstanceProposal, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.SingleTenantHsmInstanceProposal, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_single_tenant_hsm_instance_proposal + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_get_single_tenant_hsm_instance_proposal_with_metadata` + interceptor in new development instead of the `post_get_single_tenant_hsm_instance_proposal` interceptor. + When both interceptors are used, this `post_get_single_tenant_hsm_instance_proposal_with_metadata` interceptor runs after the + `post_get_single_tenant_hsm_instance_proposal` interceptor. The (possibly modified) response returned by + `post_get_single_tenant_hsm_instance_proposal` will be passed to + `post_get_single_tenant_hsm_instance_proposal_with_metadata`. + """ + return response, metadata + + def pre_list_single_tenant_hsm_instance_proposals( + self, + request: hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_single_tenant_hsm_instance_proposals + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_list_single_tenant_hsm_instance_proposals( + self, response: hsm_management.ListSingleTenantHsmInstanceProposalsResponse + ) -> hsm_management.ListSingleTenantHsmInstanceProposalsResponse: + """Post-rpc interceptor for list_single_tenant_hsm_instance_proposals + + DEPRECATED. Please use the `post_list_single_tenant_hsm_instance_proposals_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_list_single_tenant_hsm_instance_proposals` interceptor runs + before the `post_list_single_tenant_hsm_instance_proposals_with_metadata` interceptor. + """ + return response + + def post_list_single_tenant_hsm_instance_proposals_with_metadata( + self, + response: hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_single_tenant_hsm_instance_proposals + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_list_single_tenant_hsm_instance_proposals_with_metadata` + interceptor in new development instead of the `post_list_single_tenant_hsm_instance_proposals` interceptor. + When both interceptors are used, this `post_list_single_tenant_hsm_instance_proposals_with_metadata` interceptor runs after the + `post_list_single_tenant_hsm_instance_proposals` interceptor. The (possibly modified) response returned by + `post_list_single_tenant_hsm_instance_proposals` will be passed to + `post_list_single_tenant_hsm_instance_proposals_with_metadata`. + """ + return response, metadata + + def pre_list_single_tenant_hsm_instances( + self, + request: hsm_management.ListSingleTenantHsmInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ListSingleTenantHsmInstancesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_single_tenant_hsm_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_list_single_tenant_hsm_instances( + self, response: hsm_management.ListSingleTenantHsmInstancesResponse + ) -> hsm_management.ListSingleTenantHsmInstancesResponse: + """Post-rpc interceptor for list_single_tenant_hsm_instances + + DEPRECATED. Please use the `post_list_single_tenant_hsm_instances_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. This `post_list_single_tenant_hsm_instances` interceptor runs + before the `post_list_single_tenant_hsm_instances_with_metadata` interceptor. + """ + return response + + def post_list_single_tenant_hsm_instances_with_metadata( + self, + response: hsm_management.ListSingleTenantHsmInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hsm_management.ListSingleTenantHsmInstancesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_single_tenant_hsm_instances + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HsmManagement server but before it is returned to user code. + + We recommend only using this `post_list_single_tenant_hsm_instances_with_metadata` + interceptor in new development instead of the `post_list_single_tenant_hsm_instances` interceptor. + When both interceptors are used, this `post_list_single_tenant_hsm_instances_with_metadata` interceptor runs after the + `post_list_single_tenant_hsm_instances` interceptor. The (possibly modified) response returned by + `post_list_single_tenant_hsm_instances` will be passed to + `post_list_single_tenant_hsm_instances_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the HsmManagement server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the HsmManagement server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class HsmManagementRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HsmManagementRestInterceptor + + +class HsmManagementRestTransport(_BaseHsmManagementRestTransport): + """REST backend synchronous transport for HsmManagement. + + Google Cloud HSM Management Service + + Provides interfaces for managing HSM instances. + + Implements a REST model with the following objects: + + - [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + - [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudkms.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[HsmManagementRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or HsmManagementRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _ApproveSingleTenantHsmInstanceProposal( + _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal, + HsmManagementRestStub, + ): + def __hash__(self): + return hash( + "HsmManagementRestTransport.ApproveSingleTenantHsmInstanceProposal" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.ApproveSingleTenantHsmInstanceProposalResponse: + r"""Call the approve single tenant hsm + instance proposal method over HTTP. + + Args: + request (~.hsm_management.ApproveSingleTenantHsmInstanceProposalRequest): + The request object. Request message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hsm_management.ApproveSingleTenantHsmInstanceProposalResponse: + Response message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_approve_single_tenant_hsm_instance_proposal( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.ApproveSingleTenantHsmInstanceProposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ApproveSingleTenantHsmInstanceProposal", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._ApproveSingleTenantHsmInstanceProposal._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + pb_resp = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_approve_single_tenant_hsm_instance_proposal( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_approve_single_tenant_hsm_instance_proposal_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.approve_single_tenant_hsm_instance_proposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ApproveSingleTenantHsmInstanceProposal", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSingleTenantHsmInstance( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance, + HsmManagementRestStub, + ): + def __hash__(self): + return hash("HsmManagementRestTransport.CreateSingleTenantHsmInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hsm_management.CreateSingleTenantHsmInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create single tenant hsm + instance method over HTTP. + + Args: + request (~.hsm_management.CreateSingleTenantHsmInstanceRequest): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_single_tenant_hsm_instance( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.CreateSingleTenantHsmInstance", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "CreateSingleTenantHsmInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HsmManagementRestTransport._CreateSingleTenantHsmInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_single_tenant_hsm_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_create_single_tenant_hsm_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.create_single_tenant_hsm_instance", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "CreateSingleTenantHsmInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSingleTenantHsmInstanceProposal( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal, + HsmManagementRestStub, + ): + def __hash__(self): + return hash( + "HsmManagementRestTransport.CreateSingleTenantHsmInstanceProposal" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hsm_management.CreateSingleTenantHsmInstanceProposalRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create single tenant hsm + instance proposal method over HTTP. + + Args: + request (~.hsm_management.CreateSingleTenantHsmInstanceProposalRequest): + The request object. Request message for + [HsmManagement.CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_create_single_tenant_hsm_instance_proposal( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.CreateSingleTenantHsmInstanceProposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "CreateSingleTenantHsmInstanceProposal", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._CreateSingleTenantHsmInstanceProposal._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_single_tenant_hsm_instance_proposal( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_create_single_tenant_hsm_instance_proposal_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.create_single_tenant_hsm_instance_proposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "CreateSingleTenantHsmInstanceProposal", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSingleTenantHsmInstanceProposal( + _BaseHsmManagementRestTransport._BaseDeleteSingleTenantHsmInstanceProposal, + HsmManagementRestStub, + ): + def __hash__(self): + return hash( + "HsmManagementRestTransport.DeleteSingleTenantHsmInstanceProposal" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete single tenant hsm + instance proposal method over HTTP. + + Args: + request (~.hsm_management.DeleteSingleTenantHsmInstanceProposalRequest): + The request object. Request message for + [HsmManagement.DeleteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseDeleteSingleTenantHsmInstanceProposal._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_delete_single_tenant_hsm_instance_proposal( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseDeleteSingleTenantHsmInstanceProposal._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseDeleteSingleTenantHsmInstanceProposal._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.DeleteSingleTenantHsmInstanceProposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "DeleteSingleTenantHsmInstanceProposal", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._DeleteSingleTenantHsmInstanceProposal._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ExecuteSingleTenantHsmInstanceProposal( + _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal, + HsmManagementRestStub, + ): + def __hash__(self): + return hash( + "HsmManagementRestTransport.ExecuteSingleTenantHsmInstanceProposal" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the execute single tenant hsm + instance proposal method over HTTP. + + Args: + request (~.hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest): + The request object. Request message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_execute_single_tenant_hsm_instance_proposal( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.ExecuteSingleTenantHsmInstanceProposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ExecuteSingleTenantHsmInstanceProposal", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._ExecuteSingleTenantHsmInstanceProposal._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_execute_single_tenant_hsm_instance_proposal( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_execute_single_tenant_hsm_instance_proposal_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.execute_single_tenant_hsm_instance_proposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ExecuteSingleTenantHsmInstanceProposal", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSingleTenantHsmInstance( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstance, + HsmManagementRestStub, + ): + def __hash__(self): + return hash("HsmManagementRestTransport.GetSingleTenantHsmInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hsm_management.GetSingleTenantHsmInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstance: + r"""Call the get single tenant hsm + instance method over HTTP. + + Args: + request (~.hsm_management.GetSingleTenantHsmInstanceRequest): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hsm_management.SingleTenantHsmInstance: + A + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using + keys created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_single_tenant_hsm_instance( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstance._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.GetSingleTenantHsmInstance", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetSingleTenantHsmInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HsmManagementRestTransport._GetSingleTenantHsmInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hsm_management.SingleTenantHsmInstance() + pb_resp = hsm_management.SingleTenantHsmInstance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_single_tenant_hsm_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_get_single_tenant_hsm_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hsm_management.SingleTenantHsmInstance.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.get_single_tenant_hsm_instance", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetSingleTenantHsmInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSingleTenantHsmInstanceProposal( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstanceProposal, + HsmManagementRestStub, + ): + def __hash__(self): + return hash("HsmManagementRestTransport.GetSingleTenantHsmInstanceProposal") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hsm_management.GetSingleTenantHsmInstanceProposalRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.SingleTenantHsmInstanceProposal: + r"""Call the get single tenant hsm + instance proposal method over HTTP. + + Args: + request (~.hsm_management.GetSingleTenantHsmInstanceProposalRequest): + The request object. Request message for + [HsmManagement.GetSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hsm_management.SingleTenantHsmInstanceProposal: + A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstanceProposal._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_get_single_tenant_hsm_instance_proposal( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstanceProposal._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstanceProposal._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.GetSingleTenantHsmInstanceProposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetSingleTenantHsmInstanceProposal", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._GetSingleTenantHsmInstanceProposal._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hsm_management.SingleTenantHsmInstanceProposal() + pb_resp = hsm_management.SingleTenantHsmInstanceProposal.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_single_tenant_hsm_instance_proposal(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_get_single_tenant_hsm_instance_proposal_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + hsm_management.SingleTenantHsmInstanceProposal.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.get_single_tenant_hsm_instance_proposal", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetSingleTenantHsmInstanceProposal", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSingleTenantHsmInstanceProposals( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstanceProposals, + HsmManagementRestStub, + ): + def __hash__(self): + return hash( + "HsmManagementRestTransport.ListSingleTenantHsmInstanceProposals" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.ListSingleTenantHsmInstanceProposalsResponse: + r"""Call the list single tenant hsm + instance proposals method over HTTP. + + Args: + request (~.hsm_management.ListSingleTenantHsmInstanceProposalsRequest): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hsm_management.ListSingleTenantHsmInstanceProposalsResponse: + Response message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstanceProposals._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_list_single_tenant_hsm_instance_proposals( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstanceProposals._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstanceProposals._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.ListSingleTenantHsmInstanceProposals", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListSingleTenantHsmInstanceProposals", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._ListSingleTenantHsmInstanceProposals._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + pb_resp = hsm_management.ListSingleTenantHsmInstanceProposalsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_single_tenant_hsm_instance_proposals( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_list_single_tenant_hsm_instance_proposals_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hsm_management.ListSingleTenantHsmInstanceProposalsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.list_single_tenant_hsm_instance_proposals", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListSingleTenantHsmInstanceProposals", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSingleTenantHsmInstances( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstances, + HsmManagementRestStub, + ): + def __hash__(self): + return hash("HsmManagementRestTransport.ListSingleTenantHsmInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hsm_management.ListSingleTenantHsmInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hsm_management.ListSingleTenantHsmInstancesResponse: + r"""Call the list single tenant hsm + instances method over HTTP. + + Args: + request (~.hsm_management.ListSingleTenantHsmInstancesRequest): + The request object. Request message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hsm_management.ListSingleTenantHsmInstancesResponse: + Response message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstances._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_single_tenant_hsm_instances( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstances._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstances._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.ListSingleTenantHsmInstances", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListSingleTenantHsmInstances", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HsmManagementRestTransport._ListSingleTenantHsmInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hsm_management.ListSingleTenantHsmInstancesResponse() + pb_resp = hsm_management.ListSingleTenantHsmInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_single_tenant_hsm_instances(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_list_single_tenant_hsm_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + hsm_management.ListSingleTenantHsmInstancesResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementClient.list_single_tenant_hsm_instances", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListSingleTenantHsmInstances", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def approve_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ApproveSingleTenantHsmInstanceProposalRequest], + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ApproveSingleTenantHsmInstanceProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSingleTenantHsmInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.CreateSingleTenantHsmInstanceProposalRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSingleTenantHsmInstanceProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.DeleteSingleTenantHsmInstanceProposalRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSingleTenantHsmInstanceProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def execute_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExecuteSingleTenantHsmInstanceProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_single_tenant_hsm_instance( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceRequest], + hsm_management.SingleTenantHsmInstance, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSingleTenantHsmInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_single_tenant_hsm_instance_proposal( + self, + ) -> Callable[ + [hsm_management.GetSingleTenantHsmInstanceProposalRequest], + hsm_management.SingleTenantHsmInstanceProposal, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSingleTenantHsmInstanceProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_single_tenant_hsm_instance_proposals( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstanceProposalsRequest], + hsm_management.ListSingleTenantHsmInstanceProposalsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSingleTenantHsmInstanceProposals(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_single_tenant_hsm_instances( + self, + ) -> Callable[ + [hsm_management.ListSingleTenantHsmInstancesRequest], + hsm_management.ListSingleTenantHsmInstancesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSingleTenantHsmInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseHsmManagementRestTransport._BaseGetLocation, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseHsmManagementRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseHsmManagementRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.GetLocation", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseHsmManagementRestTransport._BaseListLocations, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseHsmManagementRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.ListLocations", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseHsmManagementRestTransport._BaseGetIamPolicy, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseHsmManagementRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseHsmManagementRestTransport._BaseSetIamPolicy, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseHsmManagementRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseHsmManagementRestTransport._BaseTestIamPermissions, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseTestIamPermissions._get_http_options() + ) + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseHsmManagementRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseHsmManagementRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseHsmManagementRestTransport._BaseGetOperation, HsmManagementRestStub + ): + def __hash__(self): + return hash("HsmManagementRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseHsmManagementRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseHsmManagementRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHsmManagementRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.kms_v1.HsmManagementClient.GetOperation", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HsmManagementRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.kms_v1.HsmManagementAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.kms.v1.HsmManagement", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("HsmManagementRestTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest_base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest_base.py new file mode 100644 index 000000000000..d8e5ca4a23a4 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/hsm_management/transports/rest_base.py @@ -0,0 +1,789 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.kms_v1.types import hsm_management + +from .base import DEFAULT_CLIENT_INFO, HsmManagementTransport + + +class _BaseHsmManagementRestTransport(HsmManagementTransport): + """Base REST backend transport for HsmManagement. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudkms.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseApproveSingleTenantHsmInstanceProposal: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}:approve", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.pb(request) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseApproveSingleTenantHsmInstanceProposal._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSingleTenantHsmInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/singleTenantHsmInstances", + "body": "single_tenant_hsm_instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.CreateSingleTenantHsmInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSingleTenantHsmInstanceProposal: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/singleTenantHsmInstances/*}/proposals", + "body": "single_tenant_hsm_instance_proposal", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseCreateSingleTenantHsmInstanceProposal._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSingleTenantHsmInstanceProposal: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseDeleteSingleTenantHsmInstanceProposal._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExecuteSingleTenantHsmInstanceProposal: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}:execute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest.pb(request) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseExecuteSingleTenantHsmInstanceProposal._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSingleTenantHsmInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.GetSingleTenantHsmInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSingleTenantHsmInstanceProposal: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.GetSingleTenantHsmInstanceProposalRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseGetSingleTenantHsmInstanceProposal._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSingleTenantHsmInstanceProposals: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/singleTenantHsmInstances/*}/proposals", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstanceProposals._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSingleTenantHsmInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/singleTenantHsmInstances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hsm_management.ListSingleTenantHsmInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHsmManagementRestTransport._BaseListSingleTenantHsmInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseHsmManagementRestTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py index d77cadc68663..b3450f8d89d8 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -2042,7 +2042,7 @@ async def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" + import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( parent="parent_value", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index c54edabbf56e..dbb236f716d9 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -2532,7 +2532,7 @@ def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" + import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( parent="parent_value", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py index 64cd24adf99e..7534e0f78c54 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py @@ -42,6 +42,28 @@ VerifyConnectivityRequest, VerifyConnectivityResponse, ) +from .hsm_management import ( + ApproveSingleTenantHsmInstanceProposalRequest, + ApproveSingleTenantHsmInstanceProposalResponse, + Challenge, + ChallengeReply, + CreateSingleTenantHsmInstanceMetadata, + CreateSingleTenantHsmInstanceProposalMetadata, + CreateSingleTenantHsmInstanceProposalRequest, + CreateSingleTenantHsmInstanceRequest, + DeleteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalMetadata, + ExecuteSingleTenantHsmInstanceProposalRequest, + ExecuteSingleTenantHsmInstanceProposalResponse, + GetSingleTenantHsmInstanceProposalRequest, + GetSingleTenantHsmInstanceRequest, + ListSingleTenantHsmInstanceProposalsRequest, + ListSingleTenantHsmInstanceProposalsResponse, + ListSingleTenantHsmInstancesRequest, + ListSingleTenantHsmInstancesResponse, + SingleTenantHsmInstance, + SingleTenantHsmInstanceProposal, +) from .resources import ( AccessReason, ChecksummedData, @@ -128,6 +150,26 @@ "UpdateEkmConnectionRequest", "VerifyConnectivityRequest", "VerifyConnectivityResponse", + "ApproveSingleTenantHsmInstanceProposalRequest", + "ApproveSingleTenantHsmInstanceProposalResponse", + "Challenge", + "ChallengeReply", + "CreateSingleTenantHsmInstanceMetadata", + "CreateSingleTenantHsmInstanceProposalMetadata", + "CreateSingleTenantHsmInstanceProposalRequest", + "CreateSingleTenantHsmInstanceRequest", + "DeleteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalMetadata", + "ExecuteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalResponse", + "GetSingleTenantHsmInstanceProposalRequest", + "GetSingleTenantHsmInstanceRequest", + "ListSingleTenantHsmInstanceProposalsRequest", + "ListSingleTenantHsmInstanceProposalsResponse", + "ListSingleTenantHsmInstancesRequest", + "ListSingleTenantHsmInstancesResponse", + "SingleTenantHsmInstance", + "SingleTenantHsmInstanceProposal", "ChecksummedData", "CryptoKey", "CryptoKeyVersion", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py new file mode 100644 index 000000000000..339ad96e4b64 --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py @@ -0,0 +1,1297 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.kms.v1", + manifest={ + "SingleTenantHsmInstance", + "SingleTenantHsmInstanceProposal", + "Challenge", + "ChallengeReply", + "ListSingleTenantHsmInstancesRequest", + "ListSingleTenantHsmInstancesResponse", + "GetSingleTenantHsmInstanceRequest", + "CreateSingleTenantHsmInstanceRequest", + "CreateSingleTenantHsmInstanceMetadata", + "CreateSingleTenantHsmInstanceProposalRequest", + "CreateSingleTenantHsmInstanceProposalMetadata", + "GetSingleTenantHsmInstanceProposalRequest", + "ApproveSingleTenantHsmInstanceProposalRequest", + "ApproveSingleTenantHsmInstanceProposalResponse", + "ExecuteSingleTenantHsmInstanceProposalRequest", + "ExecuteSingleTenantHsmInstanceProposalResponse", + "ExecuteSingleTenantHsmInstanceProposalMetadata", + "ListSingleTenantHsmInstanceProposalsRequest", + "ListSingleTenantHsmInstanceProposalsResponse", + "DeleteSingleTenantHsmInstanceProposalRequest", + }, +) + + +class SingleTenantHsmInstance(proto.Message): + r"""A + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + represents a single-tenant HSM instance. It can be used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [HSM_SINGLE_TENANT][CryptoKeyVersion.ProtectionLevel.HSM_SINGLE_TENANT], + as well as performing cryptographic operations using keys created + within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Attributes: + name (str): + Identifier. The resource name for this + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in the format + ``projects/*/locations/*/singleTenantHsmInstances/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + was created. + state (google.cloud.kms_v1.types.SingleTenantHsmInstance.State): + Output only. The state of the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + quorum_auth (google.cloud.kms_v1.types.SingleTenantHsmInstance.QuorumAuth): + Required. The quorum auth configuration for the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + was deleted. + unrefreshed_duration_until_disable (google.protobuf.duration_pb2.Duration): + Output only. The system-defined duration that + an instance can remain unrefreshed until it is + automatically disabled. This will have a value + of 120 days. + disable_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the instance will be + automatically disabled if not refreshed. This field is + updated upon creation and after each successful refresh + operation and enable. A [RefreshSingleTenantHsmInstance][] + operation must be made via a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + before this time otherwise the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + will become disabled. + """ + + class State(proto.Enum): + r"""The set of states of a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + Values: + STATE_UNSPECIFIED (0): + Not specified. + CREATING (1): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is being created. + PENDING_TWO_FACTOR_AUTH_REGISTRATION (2): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is waiting for 2FA keys to be registered. This can be done + by calling + [CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal] + with the [RegisterTwoFactorAuthKeys][] operation. + ACTIVE (3): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is ready to use. A + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state for all [CryptoKeys][google.cloud.kms.v1.CryptoKey] + created within the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + to be usable. + DISABLING (4): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is being disabled. + DISABLED (5): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is disabled. + DELETING (6): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + is being deleted. Requests to the instance will be rejected + in this state. + DELETED (7): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + has been deleted. + FAILED (8): + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + has failed and can not be recovered or used. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + PENDING_TWO_FACTOR_AUTH_REGISTRATION = 2 + ACTIVE = 3 + DISABLING = 4 + DISABLED = 5 + DELETING = 6 + DELETED = 7 + FAILED = 8 + + class QuorumAuth(proto.Message): + r"""Configuration for M of N quorum auth. + + Attributes: + total_approver_count (int): + Required. The total number of approvers. This + is the N value used for M of N quorum auth. Must + be greater than or equal to 3 and less than or + equal to 16. + required_approver_count (int): + Output only. The required numbers of approvers. The M value + used for M of N quorum auth. Must be greater than or equal + to 2 and less than or equal to + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + + - + + 1. + two_factor_public_key_pems (MutableSequence[str]): + Output only. The public keys associated with + the 2FA keys for M of N quorum auth. + """ + + total_approver_count: int = proto.Field( + proto.INT32, + number=1, + ) + required_approver_count: int = proto.Field( + proto.INT32, + number=2, + ) + two_factor_public_key_pems: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + quorum_auth: QuorumAuth = proto.Field( + proto.MESSAGE, + number=4, + message=QuorumAuth, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + unrefreshed_duration_until_disable: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + disable_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +class SingleTenantHsmInstanceProposal(proto.Message): + r"""A + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + represents a proposal to perform an operation on a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name for this + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + in the format + ``projects/*/locations/*/singleTenantHsmInstances/*/proposals/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + was created. + state (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.State): + Output only. The state of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + failure_reason (str): + Output only. The root cause of the most recent failure. Only + present if + [state][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.state] + is [FAILED][SingleTenantHsmInstanceProposal.FAILED]. + quorum_parameters (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.QuorumParameters): + Output only. The quorum approval parameters for the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + This field is a member of `oneof`_ ``approval_parameters``. + required_action_quorum_parameters (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.RequiredActionQuorumParameters): + Output only. Parameters for an approval of a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + that has both required challenges and a quorum. + + This field is a member of `oneof`_ ``approval_parameters``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + will expire if not approved and executed. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. The TTL for the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + Proposals will expire after this duration. + + This field is a member of `oneof`_ ``expiration``. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + was deleted. + purge_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the soft-deleted + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + will be permanently purged. This field is only populated + when the state is DELETED and will be set a time after + expiration of the proposal, i.e. >= expire_time or + (create_time + ttl). + register_two_factor_auth_keys (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.RegisterTwoFactorAuthKeys): + Register 2FA keys for the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This operation requires all N Challenges to be signed by 2FA + keys. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [PENDING_TWO_FACTOR_AUTH_REGISTRATION][google.cloud.kms.v1.SingleTenantHsmInstance.State.PENDING_TWO_FACTOR_AUTH_REGISTRATION] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + disable_single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.DisableSingleTenantHsmInstance): + Disable the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + enable_single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.EnableSingleTenantHsmInstance): + Enable the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [DISABLED][google.cloud.kms.v1.SingleTenantHsmInstance.State.DISABLED] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + delete_single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.DeleteSingleTenantHsmInstance): + Delete the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + Deleting a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + will make all [CryptoKeys][google.cloud.kms.v1.CryptoKey] + attached to the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + unusable. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [DISABLED][google.cloud.kms.v1.SingleTenantHsmInstance.State.DISABLED] + or + [PENDING_TWO_FACTOR_AUTH_REGISTRATION][google.cloud.kms.v1.SingleTenantHsmInstance.State.PENDING_TWO_FACTOR_AUTH_REGISTRATION] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + add_quorum_member (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.AddQuorumMember): + Add a quorum member to the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This will increase the + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + by 1. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + remove_quorum_member (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.RemoveQuorumMember): + Remove a quorum member from the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This will reduce + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + by 1. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + refresh_single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.RefreshSingleTenantHsmInstance): + Refreshes the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This operation must be performed periodically to keep the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + active. This operation must be performed before + [unrefreshed_duration_until_disable][google.cloud.kms.v1.SingleTenantHsmInstance.unrefreshed_duration_until_disable] + has passed. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + This field is a member of `oneof`_ ``operation``. + """ + + class State(proto.Enum): + r"""The set of states of a + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Values: + STATE_UNSPECIFIED (0): + Not specified. + CREATING (1): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + is being created. + PENDING (2): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + is pending approval. + APPROVED (3): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + has been approved. + RUNNING (4): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + is being executed. + SUCCEEDED (5): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + has been executed successfully. + FAILED (6): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + has failed. + DELETED (7): + The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + has been deleted and will be purged after the purge_time. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + PENDING = 2 + APPROVED = 3 + RUNNING = 4 + SUCCEEDED = 5 + FAILED = 6 + DELETED = 7 + + class QuorumParameters(proto.Message): + r"""Parameters of quorum approval for the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + + Attributes: + required_approver_count (int): + Output only. The required numbers of + approvers. This is the M value used for M of N + quorum auth. It is less than the number of + public keys. + challenges (MutableSequence[google.cloud.kms_v1.types.Challenge]): + Output only. The challenges to be signed by + 2FA keys for quorum auth. M of N of these + challenges are required to be signed to approve + the operation. + approved_two_factor_public_key_pems (MutableSequence[str]): + Output only. The public keys associated with the 2FA keys + that have already approved the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + by signing the challenge. + """ + + required_approver_count: int = proto.Field( + proto.INT32, + number=1, + ) + challenges: MutableSequence["Challenge"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Challenge", + ) + approved_two_factor_public_key_pems: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class RequiredActionQuorumParameters(proto.Message): + r"""Parameters for an approval that has both required challenges + and a quorum. + + Attributes: + required_challenges (MutableSequence[google.cloud.kms_v1.types.Challenge]): + Output only. A list of specific challenges + that must be signed. For some operations, this + will contain a single challenge. + required_approver_count (int): + Output only. The required number of quorum + approvers. This is the M value used for M of N + quorum auth. It is less than the number of + public keys. + quorum_challenges (MutableSequence[google.cloud.kms_v1.types.Challenge]): + Output only. The challenges to be signed by + 2FA keys for quorum auth. M of N of these + challenges are required to be signed to approve + the operation. + approved_two_factor_public_key_pems (MutableSequence[str]): + Output only. The public keys associated with the 2FA keys + that have already approved the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + by signing the challenge. + """ + + required_challenges: MutableSequence["Challenge"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Challenge", + ) + required_approver_count: int = proto.Field( + proto.INT32, + number=2, + ) + quorum_challenges: MutableSequence["Challenge"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Challenge", + ) + approved_two_factor_public_key_pems: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + class RegisterTwoFactorAuthKeys(proto.Message): + r"""Register 2FA keys for the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This operation requires all Challenges to be signed by 2FA keys. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [PENDING_TWO_FACTOR_AUTH_REGISTRATION][google.cloud.kms.v1.SingleTenantHsmInstance.State.PENDING_TWO_FACTOR_AUTH_REGISTRATION] + state to perform this operation. + + Attributes: + required_approver_count (int): + Required. The required numbers of approvers to set for the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This is the M value used for M of N quorum auth. Must be + greater than or equal to 2 and less than or equal to + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + + - + + 1. + two_factor_public_key_pems (MutableSequence[str]): + Required. The public keys associated with the + 2FA keys for M of N quorum auth. Public keys + must be associated with RSA 2048 keys. + """ + + required_approver_count: int = proto.Field( + proto.INT32, + number=1, + ) + two_factor_public_key_pems: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class DisableSingleTenantHsmInstance(proto.Message): + r"""Disable the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + """ + + class EnableSingleTenantHsmInstance(proto.Message): + r"""Enable the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [DISABLED][google.cloud.kms.v1.SingleTenantHsmInstance.State.DISABLED] + state to perform this operation. + + """ + + class DeleteSingleTenantHsmInstance(proto.Message): + r"""Delete the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + Deleting a + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + will make all [CryptoKeys][google.cloud.kms.v1.CryptoKey] attached + to the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + unusable. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must not be in the + [DELETING][google.cloud.kms.v1.SingleTenantHsmInstance.State.DELETING] + or + [DELETED][google.cloud.kms.v1.SingleTenantHsmInstance.State.DELETED] + state to perform this operation. + + """ + + class AddQuorumMember(proto.Message): + r"""Add a quorum member to the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This will increase the + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + by 1. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + Attributes: + two_factor_public_key_pem (str): + Required. The public key associated with the + 2FA key for the new quorum member to add. Public + keys must be associated with RSA 2048 keys. + """ + + two_factor_public_key_pem: str = proto.Field( + proto.STRING, + number=1, + ) + + class RemoveQuorumMember(proto.Message): + r"""Remove a quorum member from the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This will reduce + [total_approver_count][google.cloud.kms.v1.SingleTenantHsmInstance.QuorumAuth.total_approver_count] + by 1. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + Attributes: + two_factor_public_key_pem (str): + Required. The public key associated with the + 2FA key for the quorum member to remove. Public + keys must be associated with RSA 2048 keys. + """ + + two_factor_public_key_pem: str = proto.Field( + proto.STRING, + number=1, + ) + + class RefreshSingleTenantHsmInstance(proto.Message): + r"""Refreshes the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. + This operation must be performed periodically to keep the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + active. This operation must be performed before + [unrefreshed_duration_until_disable][google.cloud.kms.v1.SingleTenantHsmInstance.unrefreshed_duration_until_disable] + has passed. The + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + must be in the + [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] + state to perform this operation. + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + failure_reason: str = proto.Field( + proto.STRING, + number=4, + ) + quorum_parameters: QuorumParameters = proto.Field( + proto.MESSAGE, + number=5, + oneof="approval_parameters", + message=QuorumParameters, + ) + required_action_quorum_parameters: RequiredActionQuorumParameters = proto.Field( + proto.MESSAGE, + number=14, + oneof="approval_parameters", + message=RequiredActionQuorumParameters, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + oneof="expiration", + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + oneof="expiration", + message=duration_pb2.Duration, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + purge_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + register_two_factor_auth_keys: RegisterTwoFactorAuthKeys = proto.Field( + proto.MESSAGE, + number=8, + oneof="operation", + message=RegisterTwoFactorAuthKeys, + ) + disable_single_tenant_hsm_instance: DisableSingleTenantHsmInstance = proto.Field( + proto.MESSAGE, + number=9, + oneof="operation", + message=DisableSingleTenantHsmInstance, + ) + enable_single_tenant_hsm_instance: EnableSingleTenantHsmInstance = proto.Field( + proto.MESSAGE, + number=10, + oneof="operation", + message=EnableSingleTenantHsmInstance, + ) + delete_single_tenant_hsm_instance: DeleteSingleTenantHsmInstance = proto.Field( + proto.MESSAGE, + number=11, + oneof="operation", + message=DeleteSingleTenantHsmInstance, + ) + add_quorum_member: AddQuorumMember = proto.Field( + proto.MESSAGE, + number=12, + oneof="operation", + message=AddQuorumMember, + ) + remove_quorum_member: RemoveQuorumMember = proto.Field( + proto.MESSAGE, + number=13, + oneof="operation", + message=RemoveQuorumMember, + ) + refresh_single_tenant_hsm_instance: RefreshSingleTenantHsmInstance = proto.Field( + proto.MESSAGE, + number=17, + oneof="operation", + message=RefreshSingleTenantHsmInstance, + ) + + +class Challenge(proto.Message): + r"""A challenge to be signed by a 2FA key. + + Attributes: + challenge (bytes): + Output only. The challenge to be signed by + the 2FA key indicated by the public key. + public_key_pem (str): + Output only. The public key associated with + the 2FA key that should sign the challenge. + """ + + challenge: bytes = proto.Field( + proto.BYTES, + number=1, + ) + public_key_pem: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ChallengeReply(proto.Message): + r"""A reply to a challenge signed by a 2FA key. + + Attributes: + signed_challenge (bytes): + Required. The signed challenge associated + with the 2FA key. The signature must be + RSASSA-PKCS1 v1.5 with a SHA256 digest. + public_key_pem (str): + Required. The public key associated with the + 2FA key. + """ + + signed_challenge: bytes = proto.Field( + proto.BYTES, + number=1, + ) + public_key_pem: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSingleTenantHsmInstancesRequest(proto.Message): + r"""Request message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + to list, in the format ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + to include in the response. Further + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + can subsequently be obtained by including the + [ListSingleTenantHsmInstancesResponse.next_page_token][google.cloud.kms.v1.ListSingleTenantHsmInstancesResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListSingleTenantHsmInstancesResponse.next_page_token][google.cloud.kms.v1.ListSingleTenantHsmInstancesResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + show_deleted (bool): + Optional. If set to true, + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances] + will also return + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + in DELETED state. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListSingleTenantHsmInstancesResponse(proto.Message): + r"""Response message for + [HsmManagement.ListSingleTenantHsmInstances][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances]. + + Attributes: + single_tenant_hsm_instances (MutableSequence[google.cloud.kms_v1.types.SingleTenantHsmInstance]): + The list of + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListSingleTenantHsmInstancesRequest.page_token][google.cloud.kms.v1.ListSingleTenantHsmInstancesRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [SingleTenantHsmInstances][google.cloud.kms.v1.SingleTenantHsmInstance] + that matched the query. + + This field is not populated if + [ListSingleTenantHsmInstancesRequest.filter][google.cloud.kms.v1.ListSingleTenantHsmInstancesRequest.filter] + is applied. + """ + + @property + def raw_page(self): + return self + + single_tenant_hsm_instances: MutableSequence[ + "SingleTenantHsmInstance" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SingleTenantHsmInstance", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class GetSingleTenantHsmInstanceRequest(proto.Message): + r"""Request message for + [HsmManagement.GetSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] of + the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSingleTenantHsmInstanceRequest(proto.Message): + r"""Request message for + [HsmManagement.CreateSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance], + in the format ``projects/*/locations/*``. + single_tenant_hsm_instance_id (str): + Optional. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}``. + single_tenant_hsm_instance (google.cloud.kms_v1.types.SingleTenantHsmInstance): + Required. An + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + with initial field values. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + single_tenant_hsm_instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + single_tenant_hsm_instance: "SingleTenantHsmInstance" = proto.Field( + proto.MESSAGE, + number=3, + message="SingleTenantHsmInstance", + ) + + +class CreateSingleTenantHsmInstanceMetadata(proto.Message): + r"""Metadata message for + [CreateSingleTenantHsmInstance][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance] + long-running operation response. + + """ + + +class CreateSingleTenantHsmInstanceProposalRequest(proto.Message): + r"""Request message for + [HsmManagement.CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal]. + + Attributes: + parent (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstance.name] of + the + [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance] + associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + single_tenant_hsm_instance_proposal_id (str): + Optional. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}``. + single_tenant_hsm_instance_proposal (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal): + Required. The + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + single_tenant_hsm_instance_proposal_id: str = proto.Field( + proto.STRING, + number=2, + ) + single_tenant_hsm_instance_proposal: "SingleTenantHsmInstanceProposal" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="SingleTenantHsmInstanceProposal", + ) + ) + + +class CreateSingleTenantHsmInstanceProposalMetadata(proto.Message): + r"""Metadata message for + [CreateSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal] + long-running operation response. + + """ + + +class GetSingleTenantHsmInstanceProposalRequest(proto.Message): + r"""Request message for + [HsmManagement.GetSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ApproveSingleTenantHsmInstanceProposalRequest(proto.Message): + r"""Request message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to approve. + quorum_reply (google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply): + Required. The reply to + [QuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.QuorumParameters] + for approving the proposal. + + This field is a member of `oneof`_ ``approval_payload``. + required_action_quorum_reply (google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.RequiredActionQuorumReply): + Required. The reply to + [RequiredActionQuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.RequiredActionQuorumParameters] + for approving the proposal. + + This field is a member of `oneof`_ ``approval_payload``. + """ + + class QuorumReply(proto.Message): + r"""The reply to + [QuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.QuorumParameters] + for approving the proposal. + + Attributes: + challenge_replies (MutableSequence[google.cloud.kms_v1.types.ChallengeReply]): + Required. The challenge replies to approve the proposal. + Challenge replies can be sent across multiple requests. The + proposal will be approved when + [required_approver_count][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.QuorumParameters.required_approver_count] + challenge replies are provided. + """ + + challenge_replies: MutableSequence["ChallengeReply"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ChallengeReply", + ) + + class RequiredActionQuorumReply(proto.Message): + r"""The reply to + [RequiredActionQuorumParameters][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.RequiredActionQuorumParameters] + for approving the proposal. + + Attributes: + required_challenge_replies (MutableSequence[google.cloud.kms_v1.types.ChallengeReply]): + Required. All required challenges must be + signed for the proposal to be approved. These + can be sent across multiple requests. + quorum_challenge_replies (MutableSequence[google.cloud.kms_v1.types.ChallengeReply]): + Required. Quorum members' signed challenge replies. These + can be provided across multiple requests. The proposal will + be approved when + [required_approver_count][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.RequiredActionQuorumParameters.required_approver_count] + quorum_challenge_replies are provided and when all + required_challenge_replies are provided. + """ + + required_challenge_replies: MutableSequence[ + "ChallengeReply" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ChallengeReply", + ) + quorum_challenge_replies: MutableSequence[ + "ChallengeReply" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="ChallengeReply", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + quorum_reply: QuorumReply = proto.Field( + proto.MESSAGE, + number=2, + oneof="approval_payload", + message=QuorumReply, + ) + required_action_quorum_reply: RequiredActionQuorumReply = proto.Field( + proto.MESSAGE, + number=3, + oneof="approval_payload", + message=RequiredActionQuorumReply, + ) + + +class ApproveSingleTenantHsmInstanceProposalResponse(proto.Message): + r"""Response message for + [HsmManagement.ApproveSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal]. + + """ + + +class ExecuteSingleTenantHsmInstanceProposalRequest(proto.Message): + r"""Request message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to execute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExecuteSingleTenantHsmInstanceProposalResponse(proto.Message): + r"""Response message for + [HsmManagement.ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal]. + + """ + + +class ExecuteSingleTenantHsmInstanceProposalMetadata(proto.Message): + r"""Metadata message for + [ExecuteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal] + long-running operation response. + + """ + + +class ListSingleTenantHsmInstanceProposalsRequest(proto.Message): + r"""Request message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + + Attributes: + parent (str): + Required. The resource name of the single tenant HSM + instance associated with the + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to list, in the format + ``projects/*/locations/*/singleTenantHsmInstances/*``. + page_size (int): + Optional. Optional limit on the number of + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to include in the response. Further + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + can subsequently be obtained by including the + [ListSingleTenantHsmInstanceProposalsResponse.next_page_token][google.cloud.kms.v1.ListSingleTenantHsmInstanceProposalsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListSingleTenantHsmInstanceProposalsResponse.next_page_token][google.cloud.kms.v1.ListSingleTenantHsmInstanceProposalsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + show_deleted (bool): + Optional. If set to true, + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals] + will also return + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + in DELETED state. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListSingleTenantHsmInstanceProposalsResponse(proto.Message): + r"""Response message for + [HsmManagement.ListSingleTenantHsmInstanceProposals][google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals]. + + Attributes: + single_tenant_hsm_instance_proposals (MutableSequence[google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal]): + The list of + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListSingleTenantHsmInstanceProposalsRequest.page_token][google.cloud.kms.v1.ListSingleTenantHsmInstanceProposalsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [SingleTenantHsmInstanceProposals][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + that matched the query. + + This field is not populated if + [ListSingleTenantHsmInstanceProposalsRequest.filter][google.cloud.kms.v1.ListSingleTenantHsmInstanceProposalsRequest.filter] + is applied. + """ + + @property + def raw_page(self): + return self + + single_tenant_hsm_instance_proposals: MutableSequence[ + "SingleTenantHsmInstanceProposal" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SingleTenantHsmInstanceProposal", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class DeleteSingleTenantHsmInstanceProposalRequest(proto.Message): + r"""Request message for + [HsmManagement.DeleteSingleTenantHsmInstanceProposal][google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.SingleTenantHsmInstanceProposal.name] + of the + [SingleTenantHsmInstanceProposal][google.cloud.kms.v1.SingleTenantHsmInstanceProposal] + to delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py index 74d2c150471b..b4fc7dd9d9b3 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py @@ -61,12 +61,16 @@ class ProtectionLevel(proto.Enum): EXTERNAL_VPC (4): Crypto operations are performed in an EKM-over-VPC backend. + HSM_SINGLE_TENANT (5): + Crypto operations are performed in a + single-tenant HSM. """ PROTECTION_LEVEL_UNSPECIFIED = 0 SOFTWARE = 1 HSM = 2 EXTERNAL = 3 EXTERNAL_VPC = 4 + HSM_SINGLE_TENANT = 5 class AccessReason(proto.Enum): @@ -301,8 +305,14 @@ class CryptoKey(proto.Message): [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC], with the resource name in the format - ``projects/*/locations/*/ekmConnections/*``. Note, this list - is non-exhaustive and may apply to additional + ``projects/*/locations/*/ekmConnections/*``. Only applicable + if [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + have a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT], + with the resource name in the format + ``projects/*/locations/*/singleTenantHsmInstances/*``. Note, + this list is non-exhaustive and may apply to additional [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in the future. key_access_justifications_policy (google.cloud.kms_v1.types.KeyAccessJustificationsPolicy): @@ -1305,6 +1315,17 @@ class ImportJob(proto.Message): [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] is one with a protection level of [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. + crypto_key_backend (str): + Immutable. The resource name of the backend environment + where the key material for the wrapping key resides and + where all related cryptographic operations are performed. + Currently, this field is only populated for keys stored in + HSM_SINGLE_TENANT. Note, this list is non-exhaustive and may + apply to additional + [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in + the future. Supported resources: + + - ``"projects/*/locations/*/singleTenantHsmInstances/*"`` """ class ImportMethod(proto.Enum): @@ -1463,6 +1484,10 @@ class WrappingPublicKey(proto.Message): number=8, message="KeyOperationAttestation", ) + crypto_key_backend: str = proto.Field( + proto.STRING, + number=11, + ) class ExternalProtectionLevelOptions(proto.Message): diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py index 39df6b3387a2..f364eebb8c6b 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py @@ -2687,6 +2687,12 @@ class LocationMetadata(proto.Message): [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] can be created in this location. + hsm_single_tenant_available (bool): + Indicates whether + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT] + can be created in this location. """ hsm_available: bool = proto.Field( @@ -2697,6 +2703,10 @@ class LocationMetadata(proto.Message): proto.BOOL, number=2, ) + hsm_single_tenant_available: bool = proto.Field( + proto.BOOL, + number=3, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py new file mode 100644 index 000000000000..f07642e3408a --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ApproveSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_approve_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + quorum_reply = kms_v1.QuorumReply() + quorum_reply.challenge_replies.signed_challenge = b"signed_challenge_blob" + quorum_reply.challenge_replies.public_key_pem = "public_key_pem_value" + + request = kms_v1.ApproveSingleTenantHsmInstanceProposalRequest( + quorum_reply=quorum_reply, + name="name_value", + ) + + # Make the request + response = await client.approve_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py new file mode 100644 index 000000000000..a0a5a567fc6e --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ApproveSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_approve_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + quorum_reply = kms_v1.QuorumReply() + quorum_reply.challenge_replies.signed_challenge = b"signed_challenge_blob" + quorum_reply.challenge_replies.public_key_pem = "public_key_pem_value" + + request = kms_v1.ApproveSingleTenantHsmInstanceProposalRequest( + quorum_reply=quorum_reply, + name="name_value", + ) + + # Make the request + response = client.approve_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py new file mode 100644 index 000000000000..f656967bf37a --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSingleTenantHsmInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + single_tenant_hsm_instance = kms_v1.SingleTenantHsmInstance() + single_tenant_hsm_instance.quorum_auth.total_approver_count = 2170 + + request = kms_v1.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py new file mode 100644 index 000000000000..70646a6ef94e --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + single_tenant_hsm_instance_proposal = kms_v1.SingleTenantHsmInstanceProposal() + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.required_approver_count = ( + 2487 + ) + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.two_factor_public_key_pems = [ + "two_factor_public_key_pems_value1", + "two_factor_public_key_pems_value2", + ] + + request = kms_v1.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal=single_tenant_hsm_instance_proposal, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py new file mode 100644 index 000000000000..3f3992a30e0d --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + single_tenant_hsm_instance_proposal = kms_v1.SingleTenantHsmInstanceProposal() + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.required_approver_count = ( + 2487 + ) + single_tenant_hsm_instance_proposal.register_two_factor_auth_keys.two_factor_public_key_pems = [ + "two_factor_public_key_pems_value1", + "two_factor_public_key_pems_value2", + ] + + request = kms_v1.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal=single_tenant_hsm_instance_proposal, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py new file mode 100644 index 000000000000..50ea46b35fc6 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSingleTenantHsmInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + single_tenant_hsm_instance = kms_v1.SingleTenantHsmInstance() + single_tenant_hsm_instance.quorum_auth.total_approver_count = 2170 + + request = kms_v1.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + + # Make the request + operation = client.create_single_tenant_hsm_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py new file mode 100644 index 000000000000..888364250c95 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_delete_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + await client.delete_single_tenant_hsm_instance_proposal(request=request) + + +# [END cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py new file mode 100644 index 000000000000..c3dbf08e19bb --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_delete_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + client.delete_single_tenant_hsm_instance_proposal(request=request) + + +# [END cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py new file mode 100644 index 000000000000..927b08cd2937 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_execute_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + operation = client.execute_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py new file mode 100644 index 000000000000..e60ea7b4353d --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_execute_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + operation = client.execute_single_tenant_hsm_instance_proposal(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py new file mode 100644 index 000000000000..4ecef89c940d --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSingleTenantHsmInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_single_tenant_hsm_instance(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py new file mode 100644 index 000000000000..54a7fb9b6ac7 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + response = await client.get_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py new file mode 100644 index 000000000000..a21a98680357 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSingleTenantHsmInstanceProposal +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_single_tenant_hsm_instance_proposal(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Make the request + response = client.get_single_tenant_hsm_instance_proposal(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py new file mode 100644 index 000000000000..24062f671719 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSingleTenantHsmInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_single_tenant_hsm_instance(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_single_tenant_hsm_instance(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py new file mode 100644 index 000000000000..fa1002368118 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSingleTenantHsmInstanceProposals +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_single_tenant_hsm_instance_proposals(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instance_proposals(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py new file mode 100644 index 000000000000..a4e20f0f9403 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSingleTenantHsmInstanceProposals +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_single_tenant_hsm_instance_proposals(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instance_proposals(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py new file mode 100644 index 000000000000..6980f6ad274f --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSingleTenantHsmInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_single_tenant_hsm_instances(): + # Create a client + client = kms_v1.HsmManagementAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py new file mode 100644 index 000000000000..9049275dd10b --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSingleTenantHsmInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_single_tenant_hsm_instances(): + # Create a client + client = kms_v1.HsmManagementClient() + + # Initialize request argument(s) + request = kms_v1.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_single_tenant_hsm_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py index 8e3ec7d2865e..badaa253bb8a 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py @@ -41,7 +41,7 @@ async def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" + import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( parent="parent_value", diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py index 8eabd7ae45b8..887cba015855 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py @@ -41,7 +41,7 @@ def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" + import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( parent="parent_value", diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index dee94db20d02..15376f4251c3 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -2160,6 +2160,1489 @@ ], "title": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.approve_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ApproveSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "quorum_reply", + "type": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalResponse", + "shortName": "approve_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for ApproveSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.approve_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ApproveSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ApproveSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "quorum_reply", + "type": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.ApproveSingleTenantHsmInstanceProposalResponse", + "shortName": "approve_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for ApproveSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ApproveSingleTenantHsmInstanceProposal_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_approve_single_tenant_hsm_instance_proposal_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.create_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "CreateSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "single_tenant_hsm_instance_proposal", + "type": "google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal" + }, + { + "name": "single_tenant_hsm_instance_proposal_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for CreateSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.create_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "CreateSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "single_tenant_hsm_instance_proposal", + "type": "google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal" + }, + { + "name": "single_tenant_hsm_instance_proposal_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for CreateSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstanceProposal_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_proposal_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.create_single_tenant_hsm_instance", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "CreateSingleTenantHsmInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "single_tenant_hsm_instance", + "type": "google.cloud.kms_v1.types.SingleTenantHsmInstance" + }, + { + "name": "single_tenant_hsm_instance_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_single_tenant_hsm_instance" + }, + "description": "Sample for CreateSingleTenantHsmInstance", + "file": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.create_single_tenant_hsm_instance", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.CreateSingleTenantHsmInstance", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "CreateSingleTenantHsmInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateSingleTenantHsmInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "single_tenant_hsm_instance", + "type": "google.cloud.kms_v1.types.SingleTenantHsmInstance" + }, + { + "name": "single_tenant_hsm_instance_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_single_tenant_hsm_instance" + }, + "description": "Sample for CreateSingleTenantHsmInstance", + "file": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_CreateSingleTenantHsmInstance_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_create_single_tenant_hsm_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.delete_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "DeleteSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DeleteSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for DeleteSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.delete_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.DeleteSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "DeleteSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DeleteSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for DeleteSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_DeleteSingleTenantHsmInstanceProposal_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_delete_single_tenant_hsm_instance_proposal_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.execute_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ExecuteSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "execute_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for ExecuteSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.execute_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ExecuteSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ExecuteSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ExecuteSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "execute_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for ExecuteSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ExecuteSingleTenantHsmInstanceProposal_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_execute_single_tenant_hsm_instance_proposal_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.get_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "GetSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal", + "shortName": "get_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for GetSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.get_single_tenant_hsm_instance_proposal", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstanceProposal", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "GetSingleTenantHsmInstanceProposal" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetSingleTenantHsmInstanceProposalRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal", + "shortName": "get_single_tenant_hsm_instance_proposal" + }, + "description": "Sample for GetSingleTenantHsmInstanceProposal", + "file": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstanceProposal_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_proposal_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.get_single_tenant_hsm_instance", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "GetSingleTenantHsmInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetSingleTenantHsmInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.SingleTenantHsmInstance", + "shortName": "get_single_tenant_hsm_instance" + }, + "description": "Sample for GetSingleTenantHsmInstance", + "file": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.get_single_tenant_hsm_instance", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.GetSingleTenantHsmInstance", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "GetSingleTenantHsmInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetSingleTenantHsmInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.SingleTenantHsmInstance", + "shortName": "get_single_tenant_hsm_instance" + }, + "description": "Sample for GetSingleTenantHsmInstance", + "file": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_GetSingleTenantHsmInstance_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_get_single_tenant_hsm_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.list_single_tenant_hsm_instance_proposals", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ListSingleTenantHsmInstanceProposals" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstanceProposalsAsyncPager", + "shortName": "list_single_tenant_hsm_instance_proposals" + }, + "description": "Sample for ListSingleTenantHsmInstanceProposals", + "file": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.list_single_tenant_hsm_instance_proposals", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstanceProposals", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ListSingleTenantHsmInstanceProposals" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListSingleTenantHsmInstanceProposalsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstanceProposalsPager", + "shortName": "list_single_tenant_hsm_instance_proposals" + }, + "description": "Sample for ListSingleTenantHsmInstanceProposals", + "file": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstanceProposals_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instance_proposals_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient", + "shortName": "HsmManagementAsyncClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementAsyncClient.list_single_tenant_hsm_instances", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ListSingleTenantHsmInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstancesAsyncPager", + "shortName": "list_single_tenant_hsm_instances" + }, + "description": "Sample for ListSingleTenantHsmInstances", + "file": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.HsmManagementClient", + "shortName": "HsmManagementClient" + }, + "fullName": "google.cloud.kms_v1.HsmManagementClient.list_single_tenant_hsm_instances", + "method": { + "fullName": "google.cloud.kms.v1.HsmManagement.ListSingleTenantHsmInstances", + "service": { + "fullName": "google.cloud.kms.v1.HsmManagement", + "shortName": "HsmManagement" + }, + "shortName": "ListSingleTenantHsmInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListSingleTenantHsmInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.services.hsm_management.pagers.ListSingleTenantHsmInstancesPager", + "shortName": "list_single_tenant_hsm_instances" + }, + "description": "Sample for ListSingleTenantHsmInstances", + "file": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_HsmManagement_ListSingleTenantHsmInstances_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_hsm_management_list_single_tenant_hsm_instances_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py new file mode 100644 index 000000000000..32973c4bd748 --- /dev/null +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py @@ -0,0 +1,11292 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.kms_v1.services.hsm_management import ( + HsmManagementAsyncClient, + HsmManagementClient, + pagers, + transports, +) +from google.cloud.kms_v1.types import hsm_management + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# 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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +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 HsmManagementClient._get_default_mtls_endpoint(None) is None + assert ( + HsmManagementClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + HsmManagementClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + HsmManagementClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HsmManagementClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HsmManagementClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert HsmManagementClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HsmManagementClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HsmManagementClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + HsmManagementClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert HsmManagementClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert HsmManagementClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HsmManagementClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HsmManagementClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HsmManagementClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert HsmManagementClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert HsmManagementClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HsmManagementClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert HsmManagementClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert HsmManagementClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + HsmManagementClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert HsmManagementClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert HsmManagementClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert HsmManagementClient._get_client_cert_source(None, False) is None + assert ( + HsmManagementClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + HsmManagementClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + HsmManagementClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + HsmManagementClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + HsmManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementClient), +) +@mock.patch.object( + HsmManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HsmManagementClient._DEFAULT_UNIVERSE + default_endpoint = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + HsmManagementClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + HsmManagementClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == HsmManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HsmManagementClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + HsmManagementClient._get_api_endpoint(None, None, default_universe, "always") + == HsmManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HsmManagementClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == HsmManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HsmManagementClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + HsmManagementClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + HsmManagementClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + HsmManagementClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + HsmManagementClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + HsmManagementClient._get_universe_domain(None, None) + == HsmManagementClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + HsmManagementClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = HsmManagementClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = HsmManagementClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HsmManagementClient, "grpc"), + (HsmManagementAsyncClient, "grpc_asyncio"), + (HsmManagementClient, "rest"), + ], +) +def test_hsm_management_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.HsmManagementGrpcTransport, "grpc"), + (transports.HsmManagementGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HsmManagementRestTransport, "rest"), + ], +) +def test_hsm_management_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HsmManagementClient, "grpc"), + (HsmManagementAsyncClient, "grpc_asyncio"), + (HsmManagementClient, "rest"), + ], +) +def test_hsm_management_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) + + +def test_hsm_management_client_get_transport_class(): + transport = HsmManagementClient.get_transport_class() + available_transports = [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementRestTransport, + ] + assert transport in available_transports + + transport = HsmManagementClient.get_transport_class("grpc") + assert transport == transports.HsmManagementGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (HsmManagementClient, transports.HsmManagementGrpcTransport, "grpc"), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (HsmManagementClient, transports.HsmManagementRestTransport, "rest"), + ], +) +@mock.patch.object( + HsmManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementClient), +) +@mock.patch.object( + HsmManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementAsyncClient), +) +def test_hsm_management_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(HsmManagementClient, "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(HsmManagementClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (HsmManagementClient, transports.HsmManagementGrpcTransport, "grpc", "true"), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (HsmManagementClient, transports.HsmManagementGrpcTransport, "grpc", "false"), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (HsmManagementClient, transports.HsmManagementRestTransport, "rest", "true"), + (HsmManagementClient, transports.HsmManagementRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + HsmManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementClient), +) +@mock.patch.object( + HsmManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_hsm_management_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [HsmManagementClient, HsmManagementAsyncClient] +) +@mock.patch.object( + HsmManagementClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HsmManagementClient), +) +@mock.patch.object( + HsmManagementAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HsmManagementAsyncClient), +) +def test_hsm_management_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [HsmManagementClient, HsmManagementAsyncClient] +) +@mock.patch.object( + HsmManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementClient), +) +@mock.patch.object( + HsmManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HsmManagementAsyncClient), +) +def test_hsm_management_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HsmManagementClient._DEFAULT_UNIVERSE + default_endpoint = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HsmManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (HsmManagementClient, transports.HsmManagementGrpcTransport, "grpc"), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (HsmManagementClient, transports.HsmManagementRestTransport, "rest"), + ], +) +def test_hsm_management_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + HsmManagementClient, + transports.HsmManagementGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (HsmManagementClient, transports.HsmManagementRestTransport, "rest", None), + ], +) +def test_hsm_management_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_hsm_management_client_client_options_from_dict(): + with mock.patch( + "google.cloud.kms_v1.services.hsm_management.transports.HsmManagementGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = HsmManagementClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + HsmManagementClient, + transports.HsmManagementGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HsmManagementAsyncClient, + transports.HsmManagementGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_hsm_management_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ListSingleTenantHsmInstancesRequest, + dict, + ], +) +def test_list_single_tenant_hsm_instances(request_type, transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.ListSingleTenantHsmInstancesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + response = client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.ListSingleTenantHsmInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_single_tenant_hsm_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_single_tenant_hsm_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.ListSingleTenantHsmInstancesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_single_tenant_hsm_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_single_tenant_hsm_instances + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_single_tenant_hsm_instances + ] = mock_rpc + request = {} + client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_single_tenant_hsm_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_single_tenant_hsm_instances + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_single_tenant_hsm_instances + ] = mock_rpc + + request = {} + await client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_single_tenant_hsm_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.ListSingleTenantHsmInstancesRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstancesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.ListSingleTenantHsmInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstancesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_async_from_dict(): + await test_list_single_tenant_hsm_instances_async(request_type=dict) + + +def test_list_single_tenant_hsm_instances_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ListSingleTenantHsmInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + call.return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instances_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ListSingleTenantHsmInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstancesResponse() + ) + await client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instances_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_single_tenant_hsm_instances( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_single_tenant_hsm_instances_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instances( + hsm_management.ListSingleTenantHsmInstancesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstancesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_single_tenant_hsm_instances( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_single_tenant_hsm_instances( + hsm_management.ListSingleTenantHsmInstancesRequest(), + parent="parent_value", + ) + + +def test_list_single_tenant_hsm_instances_pager(transport_name: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_single_tenant_hsm_instances( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstance) for i in results + ) + + +def test_list_single_tenant_hsm_instances_pages(transport_name: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_single_tenant_hsm_instances(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_single_tenant_hsm_instances_async_pager(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_single_tenant_hsm_instances( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstance) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_async_pages(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_single_tenant_hsm_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.GetSingleTenantHsmInstanceRequest, + dict, + ], +) +def test_get_single_tenant_hsm_instance(request_type, transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstance( + name="name_value", + state=hsm_management.SingleTenantHsmInstance.State.CREATING, + ) + response = client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.GetSingleTenantHsmInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstance) + assert response.name == "name_value" + assert response.state == hsm_management.SingleTenantHsmInstance.State.CREATING + + +def test_get_single_tenant_hsm_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_single_tenant_hsm_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.GetSingleTenantHsmInstanceRequest( + name="name_value", + ) + + +def test_get_single_tenant_hsm_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_single_tenant_hsm_instance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_single_tenant_hsm_instance + ] = mock_rpc + request = {} + client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_single_tenant_hsm_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_single_tenant_hsm_instance + ] = mock_rpc + + request = {} + await client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.GetSingleTenantHsmInstanceRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstance( + name="name_value", + state=hsm_management.SingleTenantHsmInstance.State.CREATING, + ) + ) + response = await client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.GetSingleTenantHsmInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstance) + assert response.name == "name_value" + assert response.state == hsm_management.SingleTenantHsmInstance.State.CREATING + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_async_from_dict(): + await test_get_single_tenant_hsm_instance_async(request_type=dict) + + +def test_get_single_tenant_hsm_instance_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.GetSingleTenantHsmInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = hsm_management.SingleTenantHsmInstance() + client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.GetSingleTenantHsmInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstance() + ) + await client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_single_tenant_hsm_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_single_tenant_hsm_instance_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance( + hsm_management.GetSingleTenantHsmInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstance() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_single_tenant_hsm_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_single_tenant_hsm_instance( + hsm_management.GetSingleTenantHsmInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.CreateSingleTenantHsmInstanceRequest, + dict, + ], +) +def test_create_single_tenant_hsm_instance(request_type, transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.CreateSingleTenantHsmInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_single_tenant_hsm_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_single_tenant_hsm_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.CreateSingleTenantHsmInstanceRequest( + parent="parent_value", + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + +def test_create_single_tenant_hsm_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_single_tenant_hsm_instance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_single_tenant_hsm_instance + ] = mock_rpc + request = {} + client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_single_tenant_hsm_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_single_tenant_hsm_instance + ] = mock_rpc + + request = {} + await client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.CreateSingleTenantHsmInstanceRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance), "__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_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.CreateSingleTenantHsmInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_async_from_dict(): + await test_create_single_tenant_hsm_instance_async(request_type=dict) + + +def test_create_single_tenant_hsm_instance_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.CreateSingleTenantHsmInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.CreateSingleTenantHsmInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__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_single_tenant_hsm_instance( + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance + mock_val = hsm_management.SingleTenantHsmInstance(name="name_value") + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_id + mock_val = "single_tenant_hsm_instance_id_value" + assert arg == mock_val + + +def test_create_single_tenant_hsm_instance_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance( + hsm_management.CreateSingleTenantHsmInstanceRequest(), + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__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_single_tenant_hsm_instance( + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance + mock_val = hsm_management.SingleTenantHsmInstance(name="name_value") + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_id + mock_val = "single_tenant_hsm_instance_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_single_tenant_hsm_instance( + hsm_management.CreateSingleTenantHsmInstanceRequest(), + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.CreateSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_create_single_tenant_hsm_instance_proposal( + request_type, transport: str = "grpc" +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_single_tenant_hsm_instance_proposal_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_single_tenant_hsm_instance_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.CreateSingleTenantHsmInstanceProposalRequest( + parent="parent_value", + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + +def test_create_single_tenant_hsm_instance_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_single_tenant_hsm_instance_proposal + ] = mock_rpc + request = {} + client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_single_tenant_hsm_instance_proposal + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + await client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.CreateSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance_proposal), "__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_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_async_from_dict(): + await test_create_single_tenant_hsm_instance_proposal_async(request_type=dict) + + +def test_create_single_tenant_hsm_instance_proposal_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_proposal_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_proposal_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__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_single_tenant_hsm_instance_proposal( + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_proposal + mock_val = hsm_management.SingleTenantHsmInstanceProposal(name="name_value") + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_proposal_id + mock_val = "single_tenant_hsm_instance_proposal_id_value" + assert arg == mock_val + + +def test_create_single_tenant_hsm_instance_proposal_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance_proposal( + hsm_management.CreateSingleTenantHsmInstanceProposalRequest(), + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__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_single_tenant_hsm_instance_proposal( + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_proposal + mock_val = hsm_management.SingleTenantHsmInstanceProposal(name="name_value") + assert arg == mock_val + arg = args[0].single_tenant_hsm_instance_proposal_id + mock_val = "single_tenant_hsm_instance_proposal_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_single_tenant_hsm_instance_proposal( + hsm_management.CreateSingleTenantHsmInstanceProposalRequest(), + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_approve_single_tenant_hsm_instance_proposal( + request_type, transport: str = "grpc" +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + response = client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, hsm_management.ApproveSingleTenantHsmInstanceProposalResponse + ) + + +def test_approve_single_tenant_hsm_instance_proposal_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.approve_single_tenant_hsm_instance_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.ApproveSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + +def test_approve_single_tenant_hsm_instance_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.approve_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.approve_single_tenant_hsm_instance_proposal + ] = mock_rpc + request = {} + client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.approve_single_tenant_hsm_instance_proposal + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.approve_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + await client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + response = await client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, hsm_management.ApproveSingleTenantHsmInstanceProposalResponse + ) + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_async_from_dict(): + await test_approve_single_tenant_hsm_instance_proposal_async(request_type=dict) + + +def test_approve_single_tenant_hsm_instance_proposal_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + await client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_approve_single_tenant_hsm_instance_proposal_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.approve_single_tenant_hsm_instance_proposal( + name="name_value", + quorum_reply=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply( + signed_challenge=b"signed_challenge_blob" + ) + ] + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + assert args[ + 0 + ].quorum_reply == hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply(signed_challenge=b"signed_challenge_blob") + ] + ) + + +def test_approve_single_tenant_hsm_instance_proposal_flattened_error(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.approve_single_tenant_hsm_instance_proposal( + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest(), + name="name_value", + quorum_reply=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply( + signed_challenge=b"signed_challenge_blob" + ) + ] + ), + ) + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.approve_single_tenant_hsm_instance_proposal( + name="name_value", + quorum_reply=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply( + signed_challenge=b"signed_challenge_blob" + ) + ] + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + assert args[ + 0 + ].quorum_reply == hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply(signed_challenge=b"signed_challenge_blob") + ] + ) + + +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.approve_single_tenant_hsm_instance_proposal( + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest(), + name="name_value", + quorum_reply=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply( + signed_challenge=b"signed_challenge_blob" + ) + ] + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_execute_single_tenant_hsm_instance_proposal( + request_type, transport: str = "grpc" +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_execute_single_tenant_hsm_instance_proposal_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.execute_single_tenant_hsm_instance_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + +def test_execute_single_tenant_hsm_instance_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.execute_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.execute_single_tenant_hsm_instance_proposal + ] = mock_rpc + request = {} + client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.execute_single_tenant_hsm_instance_proposal + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.execute_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + await client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__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.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_async_from_dict(): + await test_execute_single_tenant_hsm_instance_proposal_async(request_type=dict) + + +def test_execute_single_tenant_hsm_instance_proposal_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_execute_single_tenant_hsm_instance_proposal_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__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.execute_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_execute_single_tenant_hsm_instance_proposal_flattened_error(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.execute_single_tenant_hsm_instance_proposal( + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__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.execute_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.execute_single_tenant_hsm_instance_proposal( + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.GetSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_get_single_tenant_hsm_instance_proposal(request_type, transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstanceProposal( + name="name_value", + state=hsm_management.SingleTenantHsmInstanceProposal.State.CREATING, + failure_reason="failure_reason_value", + ) + response = client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstanceProposal) + assert response.name == "name_value" + assert ( + response.state == hsm_management.SingleTenantHsmInstanceProposal.State.CREATING + ) + assert response.failure_reason == "failure_reason_value" + + +def test_get_single_tenant_hsm_instance_proposal_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_single_tenant_hsm_instance_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.GetSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + +def test_get_single_tenant_hsm_instance_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_single_tenant_hsm_instance_proposal + ] = mock_rpc + request = {} + client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_single_tenant_hsm_instance_proposal + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + await client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.GetSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstanceProposal( + name="name_value", + state=hsm_management.SingleTenantHsmInstanceProposal.State.CREATING, + failure_reason="failure_reason_value", + ) + ) + response = await client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstanceProposal) + assert response.name == "name_value" + assert ( + response.state == hsm_management.SingleTenantHsmInstanceProposal.State.CREATING + ) + assert response.failure_reason == "failure_reason_value" + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_async_from_dict(): + await test_get_single_tenant_hsm_instance_proposal_async(request_type=dict) + + +def test_get_single_tenant_hsm_instance_proposal_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = hsm_management.SingleTenantHsmInstanceProposal() + client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_proposal_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstanceProposal() + ) + await client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_proposal_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstanceProposal() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_single_tenant_hsm_instance_proposal_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance_proposal( + hsm_management.GetSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.SingleTenantHsmInstanceProposal() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstanceProposal() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_single_tenant_hsm_instance_proposal( + hsm_management.GetSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + dict, + ], +) +def test_list_single_tenant_hsm_instance_proposals( + request_type, transport: str = "grpc" +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + response = client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstanceProposalsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_single_tenant_hsm_instance_proposals_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_single_tenant_hsm_instance_proposals(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.ListSingleTenantHsmInstanceProposalsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_single_tenant_hsm_instance_proposals_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_single_tenant_hsm_instance_proposals + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_single_tenant_hsm_instance_proposals + ] = mock_rpc + request = {} + client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_single_tenant_hsm_instance_proposals + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_single_tenant_hsm_instance_proposals + ] = mock_rpc + + request = {} + await client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.ListSingleTenantHsmInstanceProposalsRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstanceProposalsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_async_from_dict(): + await test_list_single_tenant_hsm_instance_proposals_async(request_type=dict) + + +def test_list_single_tenant_hsm_instance_proposals_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + call.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_proposals_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + await client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_proposals_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_single_tenant_hsm_instance_proposals( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_single_tenant_hsm_instance_proposals_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance_proposals( + hsm_management.ListSingleTenantHsmInstanceProposalsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_single_tenant_hsm_instance_proposals( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_single_tenant_hsm_instance_proposals( + hsm_management.ListSingleTenantHsmInstanceProposalsRequest(), + parent="parent_value", + ) + + +def test_list_single_tenant_hsm_instance_proposals_pager(transport_name: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_single_tenant_hsm_instance_proposals( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstanceProposal) + for i in results + ) + + +def test_list_single_tenant_hsm_instance_proposals_pages(transport_name: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + ), + RuntimeError, + ) + pages = list(client.list_single_tenant_hsm_instance_proposals(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_single_tenant_hsm_instance_proposals_async_pager(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_single_tenant_hsm_instance_proposals( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstanceProposal) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_async_pages(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_single_tenant_hsm_instance_proposals(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_delete_single_tenant_hsm_instance_proposal( + request_type, transport: str = "grpc" +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_single_tenant_hsm_instance_proposal_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_single_tenant_hsm_instance_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hsm_management.DeleteSingleTenantHsmInstanceProposalRequest( + name="name_value", + ) + + +def test_delete_single_tenant_hsm_instance_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_single_tenant_hsm_instance_proposal + ] = mock_rpc + request = {} + client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_single_tenant_hsm_instance_proposal + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + await client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_async( + transport: str = "grpc_asyncio", + request_type=hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_async_from_dict(): + await test_delete_single_tenant_hsm_instance_proposal_async(request_type=dict) + + +def test_delete_single_tenant_hsm_instance_proposal_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = None + client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_single_tenant_hsm_instance_proposal_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_single_tenant_hsm_instance_proposal_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__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_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_single_tenant_hsm_instance_proposal_flattened_error(): + client = HsmManagementClient( + credentials=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_single_tenant_hsm_instance_proposal( + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_flattened_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__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_single_tenant_hsm_instance_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_flattened_error_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_single_tenant_hsm_instance_proposal( + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +def test_list_single_tenant_hsm_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_single_tenant_hsm_instances + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_single_tenant_hsm_instances + ] = mock_rpc + + request = {} + client.list_single_tenant_hsm_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_single_tenant_hsm_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_single_tenant_hsm_instances_rest_required_fields( + request_type=hsm_management.ListSingleTenantHsmInstancesRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_single_tenant_hsm_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_single_tenant_hsm_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.ListSingleTenantHsmInstancesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_single_tenant_hsm_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_single_tenant_hsm_instances_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_single_tenant_hsm_instances._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_single_tenant_hsm_instances_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hsm_management.ListSingleTenantHsmInstancesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_single_tenant_hsm_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/singleTenantHsmInstances" + % client.transport._host, + args[1], + ) + + +def test_list_single_tenant_hsm_instances_rest_flattened_error(transport: str = "rest"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_single_tenant_hsm_instances( + hsm_management.ListSingleTenantHsmInstancesRequest(), + parent="parent_value", + ) + + +def test_list_single_tenant_hsm_instances_rest_pager(transport: str = "rest"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstancesResponse( + single_tenant_hsm_instances=[ + hsm_management.SingleTenantHsmInstance(), + hsm_management.SingleTenantHsmInstance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + hsm_management.ListSingleTenantHsmInstancesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_single_tenant_hsm_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstance) for i in results + ) + + pages = list( + client.list_single_tenant_hsm_instances(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_single_tenant_hsm_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_single_tenant_hsm_instance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_single_tenant_hsm_instance + ] = mock_rpc + + request = {} + client.get_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_single_tenant_hsm_instance_rest_required_fields( + request_type=hsm_management.GetSingleTenantHsmInstanceRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_single_tenant_hsm_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_single_tenant_hsm_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_single_tenant_hsm_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_single_tenant_hsm_instance_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_single_tenant_hsm_instance._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_single_tenant_hsm_instance_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_single_tenant_hsm_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*}" + % client.transport._host, + args[1], + ) + + +def test_get_single_tenant_hsm_instance_rest_flattened_error(transport: str = "rest"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_single_tenant_hsm_instance( + hsm_management.GetSingleTenantHsmInstanceRequest(), + name="name_value", + ) + + +def test_create_single_tenant_hsm_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_single_tenant_hsm_instance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_single_tenant_hsm_instance + ] = mock_rpc + + request = {} + client.create_single_tenant_hsm_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_single_tenant_hsm_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_single_tenant_hsm_instance_rest_required_fields( + request_type=hsm_management.CreateSingleTenantHsmInstanceRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_single_tenant_hsm_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_single_tenant_hsm_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("single_tenant_hsm_instance_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_single_tenant_hsm_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_single_tenant_hsm_instance_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_single_tenant_hsm_instance._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("singleTenantHsmInstanceId",)) + & set( + ( + "parent", + "singleTenantHsmInstance", + ) + ) + ) + + +def test_create_single_tenant_hsm_instance_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_single_tenant_hsm_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/singleTenantHsmInstances" + % client.transport._host, + args[1], + ) + + +def test_create_single_tenant_hsm_instance_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_single_tenant_hsm_instance( + hsm_management.CreateSingleTenantHsmInstanceRequest(), + parent="parent_value", + single_tenant_hsm_instance=hsm_management.SingleTenantHsmInstance( + name="name_value" + ), + single_tenant_hsm_instance_id="single_tenant_hsm_instance_id_value", + ) + + +def test_create_single_tenant_hsm_instance_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_single_tenant_hsm_instance_proposal_rest_required_fields( + request_type=hsm_management.CreateSingleTenantHsmInstanceProposalRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("single_tenant_hsm_instance_proposal_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_single_tenant_hsm_instance_proposal(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_single_tenant_hsm_instance_proposal_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_single_tenant_hsm_instance_proposal._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == ( + set(("singleTenantHsmInstanceProposalId",)) + & set( + ( + "parent", + "singleTenantHsmInstanceProposal", + ) + ) + ) + + +def test_create_single_tenant_hsm_instance_proposal_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_single_tenant_hsm_instance_proposal(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/singleTenantHsmInstances/*}/proposals" + % client.transport._host, + args[1], + ) + + +def test_create_single_tenant_hsm_instance_proposal_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_single_tenant_hsm_instance_proposal( + hsm_management.CreateSingleTenantHsmInstanceProposalRequest(), + parent="parent_value", + single_tenant_hsm_instance_proposal=hsm_management.SingleTenantHsmInstanceProposal( + name="name_value" + ), + single_tenant_hsm_instance_proposal_id="single_tenant_hsm_instance_proposal_id_value", + ) + + +def test_approve_single_tenant_hsm_instance_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.approve_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.approve_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_approve_single_tenant_hsm_instance_proposal_rest_required_fields( + request_type=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).approve_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).approve_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.approve_single_tenant_hsm_instance_proposal(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_approve_single_tenant_hsm_instance_proposal_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.approve_single_tenant_hsm_instance_proposal._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "quorumReply", + "requiredActionQuorumReply", + ) + ) + ) + + +def test_approve_single_tenant_hsm_instance_proposal_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.approve_single_tenant_hsm_instance_proposal(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}:approve" + % client.transport._host, + args[1], + ) + + +def test_approve_single_tenant_hsm_instance_proposal_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.approve_single_tenant_hsm_instance_proposal( + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest(), + name="name_value", + quorum_reply=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.QuorumReply( + challenge_replies=[ + hsm_management.ChallengeReply( + signed_challenge=b"signed_challenge_blob" + ) + ] + ), + ) + + +def test_execute_single_tenant_hsm_instance_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.execute_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.execute_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_execute_single_tenant_hsm_instance_proposal_rest_required_fields( + request_type=hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.execute_single_tenant_hsm_instance_proposal(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_execute_single_tenant_hsm_instance_proposal_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.execute_single_tenant_hsm_instance_proposal._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_execute_single_tenant_hsm_instance_proposal_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.execute_single_tenant_hsm_instance_proposal(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}:execute" + % client.transport._host, + args[1], + ) + + +def test_execute_single_tenant_hsm_instance_proposal_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.execute_single_tenant_hsm_instance_proposal( + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +def test_get_single_tenant_hsm_instance_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_single_tenant_hsm_instance_proposal_rest_required_fields( + request_type=hsm_management.GetSingleTenantHsmInstanceProposalRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstanceProposal() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstanceProposal.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_single_tenant_hsm_instance_proposal(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_single_tenant_hsm_instance_proposal_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_single_tenant_hsm_instance_proposal._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_single_tenant_hsm_instance_proposal_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstanceProposal() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstanceProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_single_tenant_hsm_instance_proposal(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}" + % client.transport._host, + args[1], + ) + + +def test_get_single_tenant_hsm_instance_proposal_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_single_tenant_hsm_instance_proposal( + hsm_management.GetSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +def test_list_single_tenant_hsm_instance_proposals_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_single_tenant_hsm_instance_proposals + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_single_tenant_hsm_instance_proposals + ] = mock_rpc + + request = {} + client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_single_tenant_hsm_instance_proposals_rest_required_fields( + request_type=hsm_management.ListSingleTenantHsmInstanceProposalsRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_single_tenant_hsm_instance_proposals._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_single_tenant_hsm_instance_proposals._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_single_tenant_hsm_instance_proposals(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_single_tenant_hsm_instance_proposals_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_single_tenant_hsm_instance_proposals._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_single_tenant_hsm_instance_proposals_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_single_tenant_hsm_instance_proposals(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/singleTenantHsmInstances/*}/proposals" + % client.transport._host, + args[1], + ) + + +def test_list_single_tenant_hsm_instance_proposals_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_single_tenant_hsm_instance_proposals( + hsm_management.ListSingleTenantHsmInstanceProposalsRequest(), + parent="parent_value", + ) + + +def test_list_single_tenant_hsm_instance_proposals_rest_pager(transport: str = "rest"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="abc", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[], + next_page_token="def", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + ], + next_page_token="ghi", + ), + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + single_tenant_hsm_instance_proposals=[ + hsm_management.SingleTenantHsmInstanceProposal(), + hsm_management.SingleTenantHsmInstanceProposal(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + + pager = client.list_single_tenant_hsm_instance_proposals(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, hsm_management.SingleTenantHsmInstanceProposal) + for i in results + ) + + pages = list( + client.list_single_tenant_hsm_instance_proposals( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_single_tenant_hsm_instance_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_single_tenant_hsm_instance_proposal + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_single_tenant_hsm_instance_proposal + ] = mock_rpc + + request = {} + client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_single_tenant_hsm_instance_proposal_rest_required_fields( + request_type=hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, +): + transport_class = transports.HsmManagementRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_single_tenant_hsm_instance_proposal._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_single_tenant_hsm_instance_proposal(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_single_tenant_hsm_instance_proposal_rest_unset_required_fields(): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_single_tenant_hsm_instance_proposal._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_single_tenant_hsm_instance_proposal_rest_flattened(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_single_tenant_hsm_instance_proposal(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/singleTenantHsmInstances/*/proposals/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_single_tenant_hsm_instance_proposal_rest_flattened_error( + transport: str = "rest", +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_single_tenant_hsm_instance_proposal( + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HsmManagementClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HsmManagementClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HsmManagementClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HsmManagementClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HsmManagementClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.HsmManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.HsmManagementGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + transports.HsmManagementRestTransport, + ], +) +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_kind_grpc(): + transport = HsmManagementClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_single_tenant_hsm_instances_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + call.return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + client.list_single_tenant_hsm_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_single_tenant_hsm_instance_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = hsm_management.SingleTenantHsmInstance() + client.get_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_single_tenant_hsm_instance_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_single_tenant_hsm_instance_proposal_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_approve_single_tenant_hsm_instance_proposal_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + client.approve_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_single_tenant_hsm_instance_proposal_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.execute_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_single_tenant_hsm_instance_proposal_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = hsm_management.SingleTenantHsmInstanceProposal() + client.get_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_single_tenant_hsm_instance_proposals_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + call.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + client.list_single_tenant_hsm_instance_proposals(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_single_tenant_hsm_instance_proposal_empty_call_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + call.return_value = None + client.delete_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = HsmManagementAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instances_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstancesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_single_tenant_hsm_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstance( + name="name_value", + state=hsm_management.SingleTenantHsmInstance.State.CREATING, + ) + ) + await client.get_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_single_tenant_hsm_instance_proposal_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_approve_single_tenant_hsm_instance_proposal_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + await client.approve_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_execute_single_tenant_hsm_instance_proposal_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.execute_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_single_tenant_hsm_instance_proposal_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.SingleTenantHsmInstanceProposal( + name="name_value", + state=hsm_management.SingleTenantHsmInstanceProposal.State.CREATING, + failure_reason="failure_reason_value", + ) + ) + await client.get_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_single_tenant_hsm_instance_proposals_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_single_tenant_hsm_instance_proposals(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_single_tenant_hsm_instance_proposal_empty_call_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = HsmManagementClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_single_tenant_hsm_instances_rest_bad_request( + request_type=hsm_management.ListSingleTenantHsmInstancesRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_single_tenant_hsm_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ListSingleTenantHsmInstancesRequest, + dict, + ], +) +def test_list_single_tenant_hsm_instances_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstancesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.ListSingleTenantHsmInstancesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_single_tenant_hsm_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_single_tenant_hsm_instances_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, "post_list_single_tenant_hsm_instances" + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_list_single_tenant_hsm_instances_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, "pre_list_single_tenant_hsm_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.ListSingleTenantHsmInstancesRequest.pb( + hsm_management.ListSingleTenantHsmInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hsm_management.ListSingleTenantHsmInstancesResponse.to_json( + hsm_management.ListSingleTenantHsmInstancesResponse() + ) + req.return_value.content = return_value + + request = hsm_management.ListSingleTenantHsmInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hsm_management.ListSingleTenantHsmInstancesResponse() + post_with_metadata.return_value = ( + hsm_management.ListSingleTenantHsmInstancesResponse(), + metadata, + ) + + client.list_single_tenant_hsm_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_single_tenant_hsm_instance_rest_bad_request( + request_type=hsm_management.GetSingleTenantHsmInstanceRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_single_tenant_hsm_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.GetSingleTenantHsmInstanceRequest, + dict, + ], +) +def test_get_single_tenant_hsm_instance_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstance( + name="name_value", + state=hsm_management.SingleTenantHsmInstance.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_single_tenant_hsm_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstance) + assert response.name == "name_value" + assert response.state == hsm_management.SingleTenantHsmInstance.State.CREATING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_single_tenant_hsm_instance_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, "post_get_single_tenant_hsm_instance" + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_get_single_tenant_hsm_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, "pre_get_single_tenant_hsm_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.GetSingleTenantHsmInstanceRequest.pb( + hsm_management.GetSingleTenantHsmInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hsm_management.SingleTenantHsmInstance.to_json( + hsm_management.SingleTenantHsmInstance() + ) + req.return_value.content = return_value + + request = hsm_management.GetSingleTenantHsmInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hsm_management.SingleTenantHsmInstance() + post_with_metadata.return_value = ( + hsm_management.SingleTenantHsmInstance(), + metadata, + ) + + client.get_single_tenant_hsm_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_single_tenant_hsm_instance_rest_bad_request( + request_type=hsm_management.CreateSingleTenantHsmInstanceRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_single_tenant_hsm_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.CreateSingleTenantHsmInstanceRequest, + dict, + ], +) +def test_create_single_tenant_hsm_instance_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["single_tenant_hsm_instance"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "quorum_auth": { + "total_approver_count": 2170, + "required_approver_count": 2487, + "two_factor_public_key_pems": [ + "two_factor_public_key_pems_value1", + "two_factor_public_key_pems_value2", + ], + }, + "delete_time": {}, + "unrefreshed_duration_until_disable": {"seconds": 751, "nanos": 543}, + "disable_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hsm_management.CreateSingleTenantHsmInstanceRequest.meta.fields[ + "single_tenant_hsm_instance" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "single_tenant_hsm_instance" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["single_tenant_hsm_instance"][field]) + ): + del request_init["single_tenant_hsm_instance"][field][i][subfield] + else: + del request_init["single_tenant_hsm_instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_single_tenant_hsm_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_single_tenant_hsm_instance_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_create_single_tenant_hsm_instance", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_create_single_tenant_hsm_instance_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, "pre_create_single_tenant_hsm_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.CreateSingleTenantHsmInstanceRequest.pb( + hsm_management.CreateSingleTenantHsmInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = hsm_management.CreateSingleTenantHsmInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_single_tenant_hsm_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_single_tenant_hsm_instance_proposal_rest_bad_request( + request_type=hsm_management.CreateSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_single_tenant_hsm_instance_proposal(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.CreateSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_create_single_tenant_hsm_instance_proposal_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request_init["single_tenant_hsm_instance_proposal"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "failure_reason": "failure_reason_value", + "quorum_parameters": { + "required_approver_count": 2487, + "challenges": [ + { + "challenge": b"challenge_blob", + "public_key_pem": "public_key_pem_value", + } + ], + "approved_two_factor_public_key_pems": [ + "approved_two_factor_public_key_pems_value1", + "approved_two_factor_public_key_pems_value2", + ], + }, + "required_action_quorum_parameters": { + "required_challenges": {}, + "required_approver_count": 2487, + "quorum_challenges": {}, + "approved_two_factor_public_key_pems": [ + "approved_two_factor_public_key_pems_value1", + "approved_two_factor_public_key_pems_value2", + ], + }, + "expire_time": {}, + "ttl": {"seconds": 751, "nanos": 543}, + "delete_time": {}, + "purge_time": {}, + "register_two_factor_auth_keys": { + "required_approver_count": 2487, + "two_factor_public_key_pems": [ + "two_factor_public_key_pems_value1", + "two_factor_public_key_pems_value2", + ], + }, + "disable_single_tenant_hsm_instance": {}, + "enable_single_tenant_hsm_instance": {}, + "delete_single_tenant_hsm_instance": {}, + "add_quorum_member": { + "two_factor_public_key_pem": "two_factor_public_key_pem_value" + }, + "remove_quorum_member": { + "two_factor_public_key_pem": "two_factor_public_key_pem_value" + }, + "refresh_single_tenant_hsm_instance": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + hsm_management.CreateSingleTenantHsmInstanceProposalRequest.meta.fields[ + "single_tenant_hsm_instance_proposal" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "single_tenant_hsm_instance_proposal" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["single_tenant_hsm_instance_proposal"][field]) + ): + del request_init["single_tenant_hsm_instance_proposal"][field][i][ + subfield + ] + else: + del request_init["single_tenant_hsm_instance_proposal"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_single_tenant_hsm_instance_proposal(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_single_tenant_hsm_instance_proposal_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_create_single_tenant_hsm_instance_proposal", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_create_single_tenant_hsm_instance_proposal_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_create_single_tenant_hsm_instance_proposal", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.CreateSingleTenantHsmInstanceProposalRequest.pb( + hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_single_tenant_hsm_instance_proposal( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_approve_single_tenant_hsm_instance_proposal_rest_bad_request( + request_type=hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.approve_single_tenant_hsm_instance_proposal(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_approve_single_tenant_hsm_instance_proposal_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.approve_single_tenant_hsm_instance_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, hsm_management.ApproveSingleTenantHsmInstanceProposalResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_approve_single_tenant_hsm_instance_proposal_rest_interceptors( + null_interceptor, +): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_approve_single_tenant_hsm_instance_proposal", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_approve_single_tenant_hsm_instance_proposal_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_approve_single_tenant_hsm_instance_proposal", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest.pb( + hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse.to_json( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + ) + req.return_value.content = return_value + + request = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse() + ) + post_with_metadata.return_value = ( + hsm_management.ApproveSingleTenantHsmInstanceProposalResponse(), + metadata, + ) + + client.approve_single_tenant_hsm_instance_proposal( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_execute_single_tenant_hsm_instance_proposal_rest_bad_request( + request_type=hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.execute_single_tenant_hsm_instance_proposal(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_execute_single_tenant_hsm_instance_proposal_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.execute_single_tenant_hsm_instance_proposal(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_execute_single_tenant_hsm_instance_proposal_rest_interceptors( + null_interceptor, +): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_execute_single_tenant_hsm_instance_proposal", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_execute_single_tenant_hsm_instance_proposal_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_execute_single_tenant_hsm_instance_proposal", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest.pb( + hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.execute_single_tenant_hsm_instance_proposal( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_single_tenant_hsm_instance_proposal_rest_bad_request( + request_type=hsm_management.GetSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_single_tenant_hsm_instance_proposal(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.GetSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_get_single_tenant_hsm_instance_proposal_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.SingleTenantHsmInstanceProposal( + name="name_value", + state=hsm_management.SingleTenantHsmInstanceProposal.State.CREATING, + failure_reason="failure_reason_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.SingleTenantHsmInstanceProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_single_tenant_hsm_instance_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hsm_management.SingleTenantHsmInstanceProposal) + assert response.name == "name_value" + assert ( + response.state == hsm_management.SingleTenantHsmInstanceProposal.State.CREATING + ) + assert response.failure_reason == "failure_reason_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_single_tenant_hsm_instance_proposal_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_get_single_tenant_hsm_instance_proposal", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_get_single_tenant_hsm_instance_proposal_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_get_single_tenant_hsm_instance_proposal", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.GetSingleTenantHsmInstanceProposalRequest.pb( + hsm_management.GetSingleTenantHsmInstanceProposalRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hsm_management.SingleTenantHsmInstanceProposal.to_json( + hsm_management.SingleTenantHsmInstanceProposal() + ) + req.return_value.content = return_value + + request = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hsm_management.SingleTenantHsmInstanceProposal() + post_with_metadata.return_value = ( + hsm_management.SingleTenantHsmInstanceProposal(), + metadata, + ) + + client.get_single_tenant_hsm_instance_proposal( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_single_tenant_hsm_instance_proposals_rest_bad_request( + request_type=hsm_management.ListSingleTenantHsmInstanceProposalsRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_single_tenant_hsm_instance_proposals(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.ListSingleTenantHsmInstanceProposalsRequest, + dict, + ], +) +def test_list_single_tenant_hsm_instance_proposals_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hsm_management.ListSingleTenantHsmInstanceProposalsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_single_tenant_hsm_instance_proposals(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSingleTenantHsmInstanceProposalsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_single_tenant_hsm_instance_proposals_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_list_single_tenant_hsm_instance_proposals", + ) as post, mock.patch.object( + transports.HsmManagementRestInterceptor, + "post_list_single_tenant_hsm_instance_proposals_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_list_single_tenant_hsm_instance_proposals", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hsm_management.ListSingleTenantHsmInstanceProposalsRequest.pb( + hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse.to_json( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + ) + req.return_value.content = return_value + + request = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse() + ) + post_with_metadata.return_value = ( + hsm_management.ListSingleTenantHsmInstanceProposalsResponse(), + metadata, + ) + + client.list_single_tenant_hsm_instance_proposals( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_single_tenant_hsm_instance_proposal_rest_bad_request( + request_type=hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_single_tenant_hsm_instance_proposal(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest, + dict, + ], +) +def test_delete_single_tenant_hsm_instance_proposal_rest_call_success(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/singleTenantHsmInstances/sample3/proposals/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_single_tenant_hsm_instance_proposal(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_single_tenant_hsm_instance_proposal_rest_interceptors(null_interceptor): + transport = transports.HsmManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HsmManagementRestInterceptor(), + ) + client = HsmManagementClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.HsmManagementRestInterceptor, + "pre_delete_single_tenant_hsm_instance_proposal", + ) as pre: + pre.assert_not_called() + pb_message = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest.pb( + hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_single_tenant_hsm_instance_proposal( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_single_tenant_hsm_instances_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instances), "__call__" + ) as call: + client.list_single_tenant_hsm_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_single_tenant_hsm_instance_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance), "__call__" + ) as call: + client.get_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_single_tenant_hsm_instance_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance), "__call__" + ) as call: + client.create_single_tenant_hsm_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_single_tenant_hsm_instance_proposal_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + client.create_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.CreateSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_approve_single_tenant_hsm_instance_proposal_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + client.approve_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ApproveSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_single_tenant_hsm_instance_proposal_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + client.execute_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ExecuteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_single_tenant_hsm_instance_proposal_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + client.get_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.GetSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_single_tenant_hsm_instance_proposals_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_single_tenant_hsm_instance_proposals), "__call__" + ) as call: + client.list_single_tenant_hsm_instance_proposals(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.ListSingleTenantHsmInstanceProposalsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_single_tenant_hsm_instance_proposal_empty_call_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_single_tenant_hsm_instance_proposal), "__call__" + ) as call: + client.delete_single_tenant_hsm_instance_proposal(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hsm_management.DeleteSingleTenantHsmInstanceProposalRequest() + + assert args[0] == request_msg + + +def test_hsm_management_rest_lro_client(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.HsmManagementGrpcTransport, + ) + + +def test_hsm_management_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HsmManagementTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_hsm_management_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.kms_v1.services.hsm_management.transports.HsmManagementTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.HsmManagementTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_single_tenant_hsm_instances", + "get_single_tenant_hsm_instance", + "create_single_tenant_hsm_instance", + "create_single_tenant_hsm_instance_proposal", + "approve_single_tenant_hsm_instance_proposal", + "execute_single_tenant_hsm_instance_proposal", + "get_single_tenant_hsm_instance_proposal", + "list_single_tenant_hsm_instance_proposals", + "delete_single_tenant_hsm_instance_proposal", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_hsm_management_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.kms_v1.services.hsm_management.transports.HsmManagementTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HsmManagementTransport( + 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/cloudkms", + ), + quota_project_id="octopus", + ) + + +def test_hsm_management_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.kms_v1.services.hsm_management.transports.HsmManagementTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HsmManagementTransport() + adc.assert_called_once() + + +def test_hsm_management_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) + HsmManagementClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + ], +) +def test_hsm_management_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/cloudkms", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + transports.HsmManagementRestTransport, + ], +) +def test_hsm_management_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.HsmManagementGrpcTransport, grpc_helpers), + (transports.HsmManagementGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_hsm_management_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( + "cloudkms.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/cloudkms", + ), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + ], +) +def test_hsm_management_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_hsm_management_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.HsmManagementRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_hsm_management_host_no_port(transport_name): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_hsm_management_host_with_port(transport_name): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_hsm_management_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HsmManagementClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HsmManagementClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_single_tenant_hsm_instances._session + session2 = client2.transport.list_single_tenant_hsm_instances._session + assert session1 != session2 + session1 = client1.transport.get_single_tenant_hsm_instance._session + session2 = client2.transport.get_single_tenant_hsm_instance._session + assert session1 != session2 + session1 = client1.transport.create_single_tenant_hsm_instance._session + session2 = client2.transport.create_single_tenant_hsm_instance._session + assert session1 != session2 + session1 = client1.transport.create_single_tenant_hsm_instance_proposal._session + session2 = client2.transport.create_single_tenant_hsm_instance_proposal._session + assert session1 != session2 + session1 = client1.transport.approve_single_tenant_hsm_instance_proposal._session + session2 = client2.transport.approve_single_tenant_hsm_instance_proposal._session + assert session1 != session2 + session1 = client1.transport.execute_single_tenant_hsm_instance_proposal._session + session2 = client2.transport.execute_single_tenant_hsm_instance_proposal._session + assert session1 != session2 + session1 = client1.transport.get_single_tenant_hsm_instance_proposal._session + session2 = client2.transport.get_single_tenant_hsm_instance_proposal._session + assert session1 != session2 + session1 = client1.transport.list_single_tenant_hsm_instance_proposals._session + session2 = client2.transport.list_single_tenant_hsm_instance_proposals._session + assert session1 != session2 + session1 = client1.transport.delete_single_tenant_hsm_instance_proposal._session + session2 = client2.transport.delete_single_tenant_hsm_instance_proposal._session + assert session1 != session2 + + +def test_hsm_management_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HsmManagementGrpcTransport( + 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_hsm_management_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HsmManagementGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + ], +) +def test_hsm_management_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.HsmManagementGrpcTransport, + transports.HsmManagementGrpcAsyncIOTransport, + ], +) +def test_hsm_management_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_hsm_management_grpc_lro_client(): + client = HsmManagementClient( + 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_hsm_management_grpc_lro_async_client(): + client = HsmManagementAsyncClient( + 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_single_tenant_hsm_instance_path(): + project = "squid" + location = "clam" + single_tenant_hsm_instance = "whelk" + expected = "projects/{project}/locations/{location}/singleTenantHsmInstances/{single_tenant_hsm_instance}".format( + project=project, + location=location, + single_tenant_hsm_instance=single_tenant_hsm_instance, + ) + actual = HsmManagementClient.single_tenant_hsm_instance_path( + project, location, single_tenant_hsm_instance + ) + assert expected == actual + + +def test_parse_single_tenant_hsm_instance_path(): + expected = { + "project": "octopus", + "location": "oyster", + "single_tenant_hsm_instance": "nudibranch", + } + path = HsmManagementClient.single_tenant_hsm_instance_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_single_tenant_hsm_instance_path(path) + assert expected == actual + + +def test_single_tenant_hsm_instance_proposal_path(): + project = "cuttlefish" + location = "mussel" + single_tenant_hsm_instance = "winkle" + proposal = "nautilus" + expected = "projects/{project}/locations/{location}/singleTenantHsmInstances/{single_tenant_hsm_instance}/proposals/{proposal}".format( + project=project, + location=location, + single_tenant_hsm_instance=single_tenant_hsm_instance, + proposal=proposal, + ) + actual = HsmManagementClient.single_tenant_hsm_instance_proposal_path( + project, location, single_tenant_hsm_instance, proposal + ) + assert expected == actual + + +def test_parse_single_tenant_hsm_instance_proposal_path(): + expected = { + "project": "scallop", + "location": "abalone", + "single_tenant_hsm_instance": "squid", + "proposal": "clam", + } + path = HsmManagementClient.single_tenant_hsm_instance_proposal_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_single_tenant_hsm_instance_proposal_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = HsmManagementClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = HsmManagementClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = HsmManagementClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = HsmManagementClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = HsmManagementClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = HsmManagementClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = HsmManagementClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = HsmManagementClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.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 = HsmManagementClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = HsmManagementClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HsmManagementClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.HsmManagementTransport, "_prep_wrapped_messages" + ) as prep: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.HsmManagementTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = HsmManagementClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = HsmManagementClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = HsmManagementAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = HsmManagementAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = HsmManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (HsmManagementClient, transports.HsmManagementGrpcTransport), + (HsmManagementAsyncClient, transports.HsmManagementGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index bddb8f877a44..feae20edd619 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -4927,6 +4927,7 @@ def test_get_import_job(request_type, transport: str = "grpc"): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) response = client.get_import_job(request) @@ -4945,6 +4946,7 @@ def test_get_import_job(request_type, transport: str = "grpc"): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" def test_get_import_job_non_empty_request_with_auto_populated_field(): @@ -5074,6 +5076,7 @@ async def test_get_import_job_async( import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.get_import_job(request) @@ -5093,6 +5096,7 @@ async def test_get_import_job_async( ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -6688,6 +6692,7 @@ def test_create_import_job(request_type, transport: str = "grpc"): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) response = client.create_import_job(request) @@ -6706,6 +6711,7 @@ def test_create_import_job(request_type, transport: str = "grpc"): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" def test_create_import_job_non_empty_request_with_auto_populated_field(): @@ -6843,6 +6849,7 @@ async def test_create_import_job_async( import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.create_import_job(request) @@ -6862,6 +6869,7 @@ async def test_create_import_job_async( ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -18739,6 +18747,7 @@ async def test_get_import_job_empty_call_grpc_asyncio(): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) ) await client.get_import_job(request=None) @@ -18904,6 +18913,7 @@ async def test_create_import_job_empty_call_grpc_asyncio(): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) ) await client.create_import_job(request=None) @@ -20535,6 +20545,7 @@ def test_get_import_job_rest_call_success(request_type): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) # Wrap the value into a proper Response obj @@ -20558,6 +20569,7 @@ def test_get_import_job_rest_call_success(request_type): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -21543,6 +21555,7 @@ def test_create_import_job_rest_call_success(request_type): ], }, }, + "crypto_key_backend": "crypto_key_backend_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -21621,6 +21634,7 @@ def get_message_fields(field): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + crypto_key_backend="crypto_key_backend_value", ) # Wrap the value into a proper Response obj @@ -21644,6 +21658,7 @@ def get_message_fields(field): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/internal_range.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/internal_range.py index 140d2e5dcc0c..e908356a5290 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/internal_range.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/internal_range.py @@ -49,9 +49,11 @@ class InternalRange(proto.Message): See: https://google.aip.dev/122#fields-representing-resource-names create_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the internal range was created. + Output only. Time when the internal range was + created. update_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the internal range was updated. + Output only. Time when the internal range was + updated. labels (MutableMapping[str, str]): User-defined labels. description (str): @@ -89,12 +91,13 @@ class InternalRange(proto.Message): In other words, with IPv6 this field only works as a redundant parameter. target_cidr_range (MutableSequence[str]): - Optional. Can be set to narrow down or pick a - different address space while searching for a - free range. If not set, defaults to the - "10.0.0.0/8" address space. This can be used to - search in other rfc-1918 address spaces like - "172.16.0.0/12" and "192.168.0.0/16" or + Optional. Can be set to narrow down or pick a different + address space while searching for a free range. If not set, + defaults to the ["10.0.0.0/8", "172.16.0.0/12", + "192.168.0.0/16"] address space (for auto-mode networks, the + "10.0.0.0/9" range is used instead of "10.0.0.0/8"). This + can be used to target the search in other rfc-1918 address + spaces like "172.16.0.0/12" and "192.168.0.0/16" or non-rfc-1918 address spaces used in the VPC. users (MutableSequence[str]): Output only. The list of resources that refer diff --git a/packages/google-cloud-run/docs/run_v2/instances.rst b/packages/google-cloud-run/docs/run_v2/instances.rst new file mode 100644 index 000000000000..c2234dbe98fb --- /dev/null +++ b/packages/google-cloud-run/docs/run_v2/instances.rst @@ -0,0 +1,10 @@ +Instances +--------------------------- + +.. automodule:: google.cloud.run_v2.services.instances + :members: + :inherited-members: + +.. automodule:: google.cloud.run_v2.services.instances.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-run/docs/run_v2/services_.rst b/packages/google-cloud-run/docs/run_v2/services_.rst index 5492979035aa..c152f2ba9efa 100644 --- a/packages/google-cloud-run/docs/run_v2/services_.rst +++ b/packages/google-cloud-run/docs/run_v2/services_.rst @@ -5,6 +5,7 @@ Services for Google Cloud Run v2 API builds executions + instances jobs revisions services diff --git a/packages/google-cloud-run/google/cloud/run/__init__.py b/packages/google-cloud-run/google/cloud/run/__init__.py index c8d6eeacdb70..b28b62b79a3e 100644 --- a/packages/google-cloud-run/google/cloud/run/__init__.py +++ b/packages/google-cloud-run/google/cloud/run/__init__.py @@ -22,6 +22,8 @@ from google.cloud.run_v2.services.builds.client import BuildsClient from google.cloud.run_v2.services.executions.async_client import ExecutionsAsyncClient from google.cloud.run_v2.services.executions.client import ExecutionsClient +from google.cloud.run_v2.services.instances.async_client import InstancesAsyncClient +from google.cloud.run_v2.services.instances.client import InstancesClient from google.cloud.run_v2.services.jobs.async_client import JobsAsyncClient from google.cloud.run_v2.services.jobs.client import JobsClient from google.cloud.run_v2.services.revisions.async_client import RevisionsAsyncClient @@ -40,6 +42,7 @@ SubmitBuildResponse, ) from google.cloud.run_v2.types.condition import Condition +from google.cloud.run_v2.types.container_status import ContainerStatus from google.cloud.run_v2.types.execution import ( CancelExecutionRequest, DeleteExecutionRequest, @@ -49,6 +52,16 @@ ListExecutionsResponse, ) from google.cloud.run_v2.types.execution_template import ExecutionTemplate +from google.cloud.run_v2.types.instance import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + StartInstanceRequest, + StopInstanceRequest, +) from google.cloud.run_v2.types.instance_split import ( InstanceSplit, InstanceSplitAllocationType, @@ -150,6 +163,8 @@ "BuildsAsyncClient", "ExecutionsClient", "ExecutionsAsyncClient", + "InstancesClient", + "InstancesAsyncClient", "JobsClient", "JobsAsyncClient", "RevisionsClient", @@ -164,6 +179,7 @@ "SubmitBuildRequest", "SubmitBuildResponse", "Condition", + "ContainerStatus", "CancelExecutionRequest", "DeleteExecutionRequest", "Execution", @@ -171,6 +187,14 @@ "ListExecutionsRequest", "ListExecutionsResponse", "ExecutionTemplate", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GetInstanceRequest", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "StartInstanceRequest", + "StopInstanceRequest", "InstanceSplit", "InstanceSplitStatus", "InstanceSplitAllocationType", diff --git a/packages/google-cloud-run/google/cloud/run_v2/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/__init__.py index ff8e34a311aa..eff25f54b309 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/__init__.py +++ b/packages/google-cloud-run/google/cloud/run_v2/__init__.py @@ -30,6 +30,7 @@ from .services.builds import BuildsAsyncClient, BuildsClient from .services.executions import ExecutionsAsyncClient, ExecutionsClient +from .services.instances import InstancesAsyncClient, InstancesClient from .services.jobs import JobsAsyncClient, JobsClient from .services.revisions import RevisionsAsyncClient, RevisionsClient from .services.services import ServicesAsyncClient, ServicesClient @@ -37,6 +38,7 @@ from .services.worker_pools import WorkerPoolsAsyncClient, WorkerPoolsClient from .types.build import StorageSource, SubmitBuildRequest, SubmitBuildResponse from .types.condition import Condition +from .types.container_status import ContainerStatus from .types.execution import ( CancelExecutionRequest, DeleteExecutionRequest, @@ -46,6 +48,16 @@ ListExecutionsResponse, ) from .types.execution_template import ExecutionTemplate +from .types.instance import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + StartInstanceRequest, + StopInstanceRequest, +) from .types.instance_split import ( InstanceSplit, InstanceSplitAllocationType, @@ -237,6 +249,7 @@ def _get_version(dependency_name): __all__ = ( "BuildsAsyncClient", "ExecutionsAsyncClient", + "InstancesAsyncClient", "JobsAsyncClient", "RevisionsAsyncClient", "ServicesAsyncClient", @@ -251,10 +264,13 @@ def _get_version(dependency_name): "Condition", "Container", "ContainerPort", + "ContainerStatus", + "CreateInstanceRequest", "CreateJobRequest", "CreateServiceRequest", "CreateWorkerPoolRequest", "DeleteExecutionRequest", + "DeleteInstanceRequest", "DeleteJobRequest", "DeleteRevisionRequest", "DeleteServiceRequest", @@ -271,6 +287,7 @@ def _get_version(dependency_name): "GCSVolumeSource", "GRPCAction", "GetExecutionRequest", + "GetInstanceRequest", "GetJobRequest", "GetRevisionRequest", "GetServiceRequest", @@ -279,13 +296,17 @@ def _get_version(dependency_name): "HTTPGetAction", "HTTPHeader", "IngressTraffic", + "Instance", "InstanceSplit", "InstanceSplitAllocationType", "InstanceSplitStatus", + "InstancesClient", "Job", "JobsClient", "ListExecutionsRequest", "ListExecutionsResponse", + "ListInstancesRequest", + "ListInstancesResponse", "ListJobsRequest", "ListJobsResponse", "ListRevisionsRequest", @@ -313,6 +334,8 @@ def _get_version(dependency_name): "ServiceScaling", "ServicesClient", "SourceCode", + "StartInstanceRequest", + "StopInstanceRequest", "StorageSource", "SubmitBuildRequest", "SubmitBuildResponse", diff --git a/packages/google-cloud-run/google/cloud/run_v2/gapic_metadata.json b/packages/google-cloud-run/google/cloud/run_v2/gapic_metadata.json index 66dcf6dee3ce..1a8c6c711433 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/gapic_metadata.json +++ b/packages/google-cloud-run/google/cloud/run_v2/gapic_metadata.json @@ -118,6 +118,115 @@ } } }, + "Instances": { + "clients": { + "grpc": { + "libraryClient": "InstancesClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "StartInstance": { + "methods": [ + "start_instance" + ] + }, + "StopInstance": { + "methods": [ + "stop_instance" + ] + } + } + }, + "grpc-async": { + "libraryClient": "InstancesAsyncClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "StartInstance": { + "methods": [ + "start_instance" + ] + }, + "StopInstance": { + "methods": [ + "stop_instance" + ] + } + } + }, + "rest": { + "libraryClient": "InstancesClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "StartInstance": { + "methods": [ + "start_instance" + ] + }, + "StopInstance": { + "methods": [ + "stop_instance" + ] + } + } + } + } + }, "Jobs": { "clients": { "grpc": { diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/__init__.py new file mode 100644 index 000000000000..3ee363922376 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import InstancesAsyncClient +from .client import InstancesClient + +__all__ = ( + "InstancesClient", + "InstancesAsyncClient", +) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/async_client.py new file mode 100644 index 000000000000..9ef76f9d6385 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/async_client.py @@ -0,0 +1,1329 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.run_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.run_v2.services.instances import pagers +from google.cloud.run_v2.types import condition, container_status +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance +from google.cloud.run_v2.types import k8s_min, vendor_settings + +from .client import InstancesClient +from .transports.base import DEFAULT_CLIENT_INFO, InstancesTransport +from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class InstancesAsyncClient: + """The Cloud Run Instances API allows you to manage Cloud Run + Instances. + """ + + _client: InstancesClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = InstancesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = InstancesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = InstancesClient._DEFAULT_UNIVERSE + + connector_path = staticmethod(InstancesClient.connector_path) + parse_connector_path = staticmethod(InstancesClient.parse_connector_path) + crypto_key_path = staticmethod(InstancesClient.crypto_key_path) + parse_crypto_key_path = staticmethod(InstancesClient.parse_crypto_key_path) + instance_path = staticmethod(InstancesClient.instance_path) + parse_instance_path = staticmethod(InstancesClient.parse_instance_path) + policy_path = staticmethod(InstancesClient.policy_path) + parse_policy_path = staticmethod(InstancesClient.parse_policy_path) + secret_path = staticmethod(InstancesClient.secret_path) + parse_secret_path = staticmethod(InstancesClient.parse_secret_path) + secret_version_path = staticmethod(InstancesClient.secret_version_path) + parse_secret_version_path = staticmethod(InstancesClient.parse_secret_version_path) + common_billing_account_path = staticmethod( + InstancesClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + InstancesClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(InstancesClient.common_folder_path) + parse_common_folder_path = staticmethod(InstancesClient.parse_common_folder_path) + common_organization_path = staticmethod(InstancesClient.common_organization_path) + parse_common_organization_path = staticmethod( + InstancesClient.parse_common_organization_path + ) + common_project_path = staticmethod(InstancesClient.common_project_path) + parse_common_project_path = staticmethod(InstancesClient.parse_common_project_path) + common_location_path = staticmethod(InstancesClient.common_location_path) + parse_common_location_path = staticmethod( + InstancesClient.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: + InstancesAsyncClient: The constructed client. + """ + return InstancesClient.from_service_account_info.__func__(InstancesAsyncClient, 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: + InstancesAsyncClient: The constructed client. + """ + return InstancesClient.from_service_account_file.__func__(InstancesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return InstancesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> InstancesTransport: + """Returns the transport used by the client instance. + + Returns: + InstancesTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = InstancesClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, InstancesTransport, Callable[..., InstancesTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the instances async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,InstancesTransport,Callable[..., InstancesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the InstancesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = InstancesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.run_v2.InstancesAsyncClient`.", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.run.v2.Instances", + "credentialsType": None, + }, + ) + + async def create_instance( + self, + request: Optional[Union[gcr_instance.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[gcr_instance.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_create_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + instance = run_v2.Instance() + instance.containers.image = "image_value" + + request = run_v2.CreateInstanceRequest( + parent="parent_value", + instance=instance, + instance_id="instance_id_value", + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.CreateInstanceRequest, dict]]): + The request object. + parent (:class:`str`): + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.run_v2.types.Instance`): + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcr_instance.CreateInstanceRequest): + request = gcr_instance.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_instance + ] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcr_instance.Instance, + metadata_type=gcr_instance.Instance, + ) + + # Done; return the response. + return response + + async def delete_instance( + self, + request: Optional[Union[instance.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Instance + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_delete_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.DeleteInstanceRequest, dict]]): + The request object. + name (:class:`str`): + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.DeleteInstanceRequest): + request = instance.DeleteInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.delete_instance + ] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + async def get_instance( + self, + request: Optional[Union[instance.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Gets a Instance + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_get_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.GetInstanceRequest, dict]]): + The request object. + name (:class:`str`): + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.run_v2.types.Instance: + A Cloud Run Instance represents a + single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.GetInstanceRequest): + request = instance.GetInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.get_instance + ] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_instances( + self, + request: Optional[Union[instance.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesAsyncPager: + r"""Lists Instances. Results are sorted by creation time, + descending. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_list_instances(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.ListInstancesRequest, dict]]): + The request object. Request message for retrieving a list + of Instances. + parent (:class:`str`): + Required. The location and project to + list resources on. Format: + projects/{project}/locations/{location}, + where {project} can be project id or + number. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.run_v2.services.instances.pagers.ListInstancesAsyncPager: + Response message containing a list of + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.ListInstancesRequest): + request = instance.ListInstancesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.list_instances + ] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_instance( + self, + request: Optional[Union[instance.StopInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Stops an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_stop_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.StopInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.StopInstanceRequest, dict]]): + The request object. Request message for deleting an + Instance. + name (:class:`str`): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.StopInstanceRequest): + request = instance.StopInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.stop_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + async def start_instance( + self, + request: Optional[Union[instance.StartInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Starts an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + async def sample_start_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.StartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.start_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.run_v2.types.StartInstanceRequest, dict]]): + The request object. Request message for starting an + Instance. + name (:class:`str`): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.StartInstanceRequest): + request = instance.StartInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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._client._transport._wrapped_methods[ + self._client._transport.start_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def wait_operation( + self, + request: Optional[operations_pb2.WaitOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Waits until the specified long-running operation is done or reaches at most + a specified timeout, returning the latest state. + + If the operation is already done, the latest state is immediately returned. + If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + timeout is used. If the server does not support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.WaitOperationRequest`): + The request object. Request message for + `WaitOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.WaitOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "InstancesAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("InstancesAsyncClient",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/client.py new file mode 100644 index 000000000000..d2ed2a95df9f --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/client.py @@ -0,0 +1,1861 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.run_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.run_v2.services.instances import pagers +from google.cloud.run_v2.types import condition, container_status +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance +from google.cloud.run_v2.types import k8s_min, vendor_settings + +from .transports.base import DEFAULT_CLIENT_INFO, InstancesTransport +from .transports.grpc import InstancesGrpcTransport +from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport +from .transports.rest import InstancesRestTransport + + +class InstancesClientMeta(type): + """Metaclass for the Instances 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[InstancesTransport]] + _transport_registry["grpc"] = InstancesGrpcTransport + _transport_registry["grpc_asyncio"] = InstancesGrpcAsyncIOTransport + _transport_registry["rest"] = InstancesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[InstancesTransport]: + """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 InstancesClient(metaclass=InstancesClientMeta): + """The Cloud Run Instances API allows you to manage Cloud Run + Instances. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "run.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "run.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstancesClient: 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: + InstancesClient: 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) -> InstancesTransport: + """Returns the transport used by the client instance. + + Returns: + InstancesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def connector_path( + project: str, + location: str, + connector: str, + ) -> str: + """Returns a fully-qualified connector string.""" + return "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) + + @staticmethod + def parse_connector_path(path: str) -> Dict[str, str]: + """Parses a connector path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str, str]: + """Parses a instance path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def policy_path( + project: str, + ) -> str: + """Returns a fully-qualified policy string.""" + return "projects/{project}/policy".format( + project=project, + ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str, str]: + """Parses a policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/policy$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_path( + project: str, + secret: str, + ) -> str: + """Returns a fully-qualified secret string.""" + return "projects/{project}/secrets/{secret}".format( + project=project, + secret=secret, + ) + + @staticmethod + def parse_secret_path(path: str) -> Dict[str, str]: + """Parses a secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/secrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path( + project: str, + secret: str, + version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?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 {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = InstancesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = InstancesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = InstancesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = InstancesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = InstancesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, InstancesTransport, Callable[..., InstancesTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the instances client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,InstancesTransport,Callable[..., InstancesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the InstancesTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = InstancesClient._read_environment_variables() + self._client_cert_source = InstancesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = InstancesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, InstancesTransport) + if transport_provided: + # transport is a InstancesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(InstancesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or InstancesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[InstancesTransport], Callable[..., InstancesTransport] + ] = ( + InstancesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., InstancesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.run_v2.InstancesClient`.", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.run.v2.Instances", + "credentialsType": None, + }, + ) + + def create_instance( + self, + request: Optional[Union[gcr_instance.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[gcr_instance.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_create_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + instance = run_v2.Instance() + instance.containers.image = "image_value" + + request = run_v2.CreateInstanceRequest( + parent="parent_value", + instance=instance, + instance_id="instance_id_value", + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.CreateInstanceRequest, dict]): + The request object. + parent (str): + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.run_v2.types.Instance): + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcr_instance.CreateInstanceRequest): + request = gcr_instance.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcr_instance.Instance, + metadata_type=gcr_instance.Instance, + ) + + # Done; return the response. + return response + + def delete_instance( + self, + request: Optional[Union[instance.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a Instance + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_delete_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.DeleteInstanceRequest, dict]): + The request object. + name (str): + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.DeleteInstanceRequest): + request = instance.DeleteInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_instance] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + def get_instance( + self, + request: Optional[Union[instance.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Gets a Instance + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_get_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.GetInstanceRequest, dict]): + The request object. + name (str): + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.run_v2.types.Instance: + A Cloud Run Instance represents a + single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.GetInstanceRequest): + request = instance.GetInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_instance] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_instances( + self, + request: Optional[Union[instance.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: + r"""Lists Instances. Results are sorted by creation time, + descending. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_list_instances(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.run_v2.types.ListInstancesRequest, dict]): + The request object. Request message for retrieving a list + of Instances. + parent (str): + Required. The location and project to + list resources on. Format: + projects/{project}/locations/{location}, + where {project} can be project id or + number. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.run_v2.services.instances.pagers.ListInstancesPager: + Response message containing a list of + Instances. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.ListInstancesRequest): + request = instance.ListInstancesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_instances] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_instance( + self, + request: Optional[Union[instance.StopInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Stops an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_stop_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.StopInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.StopInstanceRequest, dict]): + The request object. Request message for deleting an + Instance. + name (str): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.StopInstanceRequest): + request = instance.StopInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + def start_instance( + self, + request: Optional[Union[instance.StartInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Starts an Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import run_v2 + + def sample_start_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.StartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.start_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.run_v2.types.StartInstanceRequest, dict]): + The request object. Request message for starting an + Instance. + name (str): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.run_v2.types.Instance` A Cloud Run Instance represents a single group of containers running in a + region. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.StartInstanceRequest): + request = instance.StartInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + instance.Instance, + metadata_type=instance.Instance, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "InstancesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def wait_operation( + self, + request: Optional[operations_pb2.WaitOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Waits until the specified long-running operation is done or reaches at most + a specified timeout, returning the latest state. + + If the operation is already done, the latest state is immediately returned. + If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + timeout is used. If the server does not support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.WaitOperationRequest`): + The request object. Request message for + `WaitOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.WaitOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.wait_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("InstancesClient",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/pagers.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/pagers.py new file mode 100644 index 000000000000..cd415816e4af --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.run_v2.types import instance + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.run_v2.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.run_v2.types.ListInstancesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., instance.ListInstancesResponse], + request: instance.ListInstancesRequest, + response: instance.ListInstancesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.run_v2.types.ListInstancesRequest): + The initial request object. + response (google.cloud.run_v2.types.ListInstancesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = instance.ListInstancesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[instance.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[instance.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.run_v2.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.run_v2.types.ListInstancesResponse` + attributes are available on the 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[instance.ListInstancesResponse]], + request: instance.ListInstancesRequest, + response: instance.ListInstancesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.run_v2.types.ListInstancesRequest): + The initial request object. + response (google.cloud.run_v2.types.ListInstancesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = instance.ListInstancesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[instance.ListInstancesResponse]: + 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, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[instance.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/README.rst new file mode 100644 index 000000000000..452ca471f507 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`InstancesTransport` is the ABC for all transports. +- public child `InstancesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `InstancesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseInstancesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `InstancesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/__init__.py new file mode 100644 index 000000000000..0bbe4486f14c --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 InstancesTransport +from .grpc import InstancesGrpcTransport +from .grpc_asyncio import InstancesGrpcAsyncIOTransport +from .rest import InstancesRestInterceptor, InstancesRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[InstancesTransport]] +_transport_registry["grpc"] = InstancesGrpcTransport +_transport_registry["grpc_asyncio"] = InstancesGrpcAsyncIOTransport +_transport_registry["rest"] = InstancesRestTransport + +__all__ = ( + "InstancesTransport", + "InstancesGrpcTransport", + "InstancesGrpcAsyncIOTransport", + "InstancesRestTransport", + "InstancesRestInterceptor", +) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/base.py new file mode 100644 index 000000000000..8158fa33297c --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/base.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.run_v2 import gapic_version as package_version +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class InstancesTransport(abc.ABC): + """Abstract transport class for Instances.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "run.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.stop_instance: gapic_v1.method.wrap_method( + self.stop_instance, + default_timeout=None, + client_info=client_info, + ), + self.start_instance: gapic_v1.method.wrap_method( + self.start_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_instance( + self, + ) -> Callable[ + [gcr_instance.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_instance( + self, + ) -> Callable[ + [instance.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_instance( + self, + ) -> Callable[ + [instance.GetInstanceRequest], + Union[instance.Instance, Awaitable[instance.Instance]], + ]: + raise NotImplementedError() + + @property + def list_instances( + self, + ) -> Callable[ + [instance.ListInstancesRequest], + Union[ + instance.ListInstancesResponse, Awaitable[instance.ListInstancesResponse] + ], + ]: + raise NotImplementedError() + + @property + def stop_instance( + self, + ) -> Callable[ + [instance.StopInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def start_instance( + self, + ) -> Callable[ + [instance.StartInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def wait_operation( + self, + ) -> Callable[ + [operations_pb2.WaitOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("InstancesTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc.py new file mode 100644 index 000000000000..2f4cd2443b15 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance + +from .base import DEFAULT_CLIENT_INFO, InstancesTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class InstancesGrpcTransport(InstancesTransport): + """gRPC backend transport for Instances. + + The Cloud Run Instances API allows you to manage Cloud Run + Instances. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "run.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "run.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_instance( + self, + ) -> Callable[[gcr_instance.CreateInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Creates an Instance. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance" not in self._stubs: + self._stubs["create_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/CreateInstance", + request_serializer=gcr_instance.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_instance"] + + @property + def delete_instance( + self, + ) -> Callable[[instance.DeleteInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a Instance + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance" not in self._stubs: + self._stubs["delete_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/DeleteInstance", + request_serializer=instance.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_instance"] + + @property + def get_instance( + self, + ) -> Callable[[instance.GetInstanceRequest], instance.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets a Instance + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_instance" not in self._stubs: + self._stubs["get_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/GetInstance", + request_serializer=instance.GetInstanceRequest.serialize, + response_deserializer=instance.Instance.deserialize, + ) + return self._stubs["get_instance"] + + @property + def list_instances( + self, + ) -> Callable[[instance.ListInstancesRequest], instance.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances. Results are sorted by creation time, + descending. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_instances" not in self._stubs: + self._stubs["list_instances"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/ListInstances", + request_serializer=instance.ListInstancesRequest.serialize, + response_deserializer=instance.ListInstancesResponse.deserialize, + ) + return self._stubs["list_instances"] + + @property + def stop_instance( + self, + ) -> Callable[[instance.StopInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the stop instance method over gRPC. + + Stops an Instance. + + Returns: + Callable[[~.StopInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance" not in self._stubs: + self._stubs["stop_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/StopInstance", + request_serializer=instance.StopInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["stop_instance"] + + @property + def start_instance( + self, + ) -> Callable[[instance.StartInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the start instance method over gRPC. + + Starts an Instance. + + Returns: + Callable[[~.StartInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_instance" not in self._stubs: + self._stubs["start_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/StartInstance", + request_serializer=instance.StartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_instance"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def wait_operation( + self, + ) -> Callable[[operations_pb2.WaitOperationRequest], None]: + r"""Return a callable for the wait_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "wait_operation" not in self._stubs: + self._stubs["wait_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/WaitOperation", + request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["wait_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("InstancesGrpcTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2ae829508873 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/grpc_asyncio.py @@ -0,0 +1,654 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance + +from .base import DEFAULT_CLIENT_INFO, InstancesTransport +from .grpc import InstancesGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class InstancesGrpcAsyncIOTransport(InstancesTransport): + """gRPC AsyncIO backend transport for Instances. + + The Cloud Run Instances API allows you to manage Cloud Run + Instances. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "run.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_instance( + self, + ) -> Callable[ + [gcr_instance.CreateInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create instance method over gRPC. + + Creates an Instance. + + Returns: + Callable[[~.CreateInstanceRequest], + 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_instance" not in self._stubs: + self._stubs["create_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/CreateInstance", + request_serializer=gcr_instance.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_instance"] + + @property + def delete_instance( + self, + ) -> Callable[ + [instance.DeleteInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a Instance + + Returns: + Callable[[~.DeleteInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_instance" not in self._stubs: + self._stubs["delete_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/DeleteInstance", + request_serializer=instance.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_instance"] + + @property + def get_instance( + self, + ) -> Callable[[instance.GetInstanceRequest], Awaitable[instance.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets a Instance + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_instance" not in self._stubs: + self._stubs["get_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/GetInstance", + request_serializer=instance.GetInstanceRequest.serialize, + response_deserializer=instance.Instance.deserialize, + ) + return self._stubs["get_instance"] + + @property + def list_instances( + self, + ) -> Callable[ + [instance.ListInstancesRequest], Awaitable[instance.ListInstancesResponse] + ]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances. Results are sorted by creation time, + descending. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_instances" not in self._stubs: + self._stubs["list_instances"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/ListInstances", + request_serializer=instance.ListInstancesRequest.serialize, + response_deserializer=instance.ListInstancesResponse.deserialize, + ) + return self._stubs["list_instances"] + + @property + def stop_instance( + self, + ) -> Callable[[instance.StopInstanceRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the stop instance method over gRPC. + + Stops an Instance. + + Returns: + Callable[[~.StopInstanceRequest], + 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 "stop_instance" not in self._stubs: + self._stubs["stop_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/StopInstance", + request_serializer=instance.StopInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["stop_instance"] + + @property + def start_instance( + self, + ) -> Callable[[instance.StartInstanceRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the start instance method over gRPC. + + Starts an Instance. + + Returns: + Callable[[~.StartInstanceRequest], + 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 "start_instance" not in self._stubs: + self._stubs["start_instance"] = self._logged_channel.unary_unary( + "/google.cloud.run.v2.Instances/StartInstance", + request_serializer=instance.StartInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_instance"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_instance: self._wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: self._wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: self._wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.list_instances: self._wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.stop_instance: self._wrap_method( + self.stop_instance, + default_timeout=None, + client_info=client_info, + ), + self.start_instance: self._wrap_method( + self.start_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def wait_operation( + self, + ) -> Callable[[operations_pb2.WaitOperationRequest], None]: + r"""Return a callable for the wait_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "wait_operation" not in self._stubs: + self._stubs["wait_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/WaitOperation", + request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["wait_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("InstancesGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest.py new file mode 100644 index 000000000000..426480678be0 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest.py @@ -0,0 +1,2181 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseInstancesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class InstancesRestInterceptor: + """Interceptor for Instances. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the InstancesRestTransport. + + .. code-block:: python + class MyCustomInstancesInterceptor(InstancesRestInterceptor): + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_instance(self, response): + logging.log(f"Received response: {response}") + return response + + transport = InstancesRestTransport(interceptor=MyCustomInstancesInterceptor()) + client = InstancesClient(transport=transport) + + + """ + + def pre_create_instance( + self, + request: gcr_instance.CreateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcr_instance.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + DEPRECATED. Please use the `post_create_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_create_instance` interceptor runs + before the `post_create_instance_with_metadata` interceptor. + """ + return response + + def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_create_instance_with_metadata` + interceptor in new development instead of the `post_create_instance` interceptor. + When both interceptors are used, this `post_create_instance_with_metadata` interceptor runs after the + `post_create_instance` interceptor. The (possibly modified) response returned by + `post_create_instance` will be passed to + `post_create_instance_with_metadata`. + """ + return response, metadata + + def pre_delete_instance( + self, + request: instance.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + DEPRECATED. Please use the `post_delete_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_delete_instance` interceptor runs + before the `post_delete_instance_with_metadata` interceptor. + """ + return response + + def post_delete_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_delete_instance_with_metadata` + interceptor in new development instead of the `post_delete_instance` interceptor. + When both interceptors are used, this `post_delete_instance_with_metadata` interceptor runs after the + `post_delete_instance` interceptor. The (possibly modified) response returned by + `post_delete_instance` will be passed to + `post_delete_instance_with_metadata`. + """ + return response, metadata + + def pre_get_instance( + self, + request: instance.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_get_instance(self, response: instance.Instance) -> instance.Instance: + """Post-rpc interceptor for get_instance + + DEPRECATED. Please use the `post_get_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_get_instance` interceptor runs + before the `post_get_instance_with_metadata` interceptor. + """ + return response + + def post_get_instance_with_metadata( + self, + response: instance.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_get_instance_with_metadata` + interceptor in new development instead of the `post_get_instance` interceptor. + When both interceptors are used, this `post_get_instance_with_metadata` interceptor runs after the + `post_get_instance` interceptor. The (possibly modified) response returned by + `post_get_instance` will be passed to + `post_get_instance_with_metadata`. + """ + return response, metadata + + def pre_list_instances( + self, + request: instance.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_list_instances( + self, response: instance.ListInstancesResponse + ) -> instance.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + DEPRECATED. Please use the `post_list_instances_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_list_instances` interceptor runs + before the `post_list_instances_with_metadata` interceptor. + """ + return response + + def post_list_instances_with_metadata( + self, + response: instance.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_instances + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_list_instances_with_metadata` + interceptor in new development instead of the `post_list_instances` interceptor. + When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the + `post_list_instances` interceptor. The (possibly modified) response returned by + `post_list_instances` will be passed to + `post_list_instances_with_metadata`. + """ + return response, metadata + + def pre_start_instance( + self, + request: instance.StartInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.StartInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for start_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_start_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for start_instance + + DEPRECATED. Please use the `post_start_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_start_instance` interceptor runs + before the `post_start_instance_with_metadata` interceptor. + """ + return response + + def post_start_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for start_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_start_instance_with_metadata` + interceptor in new development instead of the `post_start_instance` interceptor. + When both interceptors are used, this `post_start_instance_with_metadata` interceptor runs after the + `post_start_instance` interceptor. The (possibly modified) response returned by + `post_start_instance` will be passed to + `post_start_instance_with_metadata`. + """ + return response, metadata + + def pre_stop_instance( + self, + request: instance.StopInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.StopInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for stop_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_stop_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_instance + + DEPRECATED. Please use the `post_stop_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_stop_instance` interceptor runs + before the `post_stop_instance_with_metadata` interceptor. + """ + return response + + def post_stop_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for stop_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_stop_instance_with_metadata` + interceptor in new development instead of the `post_stop_instance` interceptor. + When both interceptors are used, this `post_stop_instance_with_metadata` interceptor runs after the + `post_stop_instance` interceptor. The (possibly modified) response returned by + `post_stop_instance` will be passed to + `post_stop_instance_with_metadata`. + """ + return response, metadata + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Instances server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Instances server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Instances server but before + it is returned to user code. + """ + return response + + def pre_wait_operation( + self, + request: operations_pb2.WaitOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for wait_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_wait_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for wait_operation + + Override in a subclass to manipulate the response + after it is returned by the Instances server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class InstancesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: InstancesRestInterceptor + + +class InstancesRestTransport(_BaseInstancesRestTransport): + """REST backend synchronous transport for Instances. + + The Cloud Run Instances API allows you to manage Cloud Run + Instances. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[InstancesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or InstancesRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ], + "google.longrunning.Operations.WaitOperation": [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateInstance( + _BaseInstancesRestTransport._BaseCreateInstance, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcr_instance.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.gcr_instance.CreateInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseCreateInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_instance(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseInstancesRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.CreateInstance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "CreateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.create_instance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "CreateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteInstance( + _BaseInstancesRestTransport._BaseDeleteInstance, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.instance.DeleteInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseDeleteInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.DeleteInstance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "DeleteInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.delete_instance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "DeleteInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetInstance(_BaseInstancesRestTransport._BaseGetInstance, InstancesRestStub): + def __hash__(self): + return hash("InstancesRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.instance.GetInstanceRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.Instance: + A Cloud Run Instance represents a + single group of containers running in a + region. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseGetInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_instance(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.GetInstance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "GetInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.Instance() + pb_resp = instance.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.Instance.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.get_instance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "GetInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListInstances( + _BaseInstancesRestTransport._BaseListInstances, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.instance.ListInstancesRequest): + The request object. Request message for retrieving a list + of Instances. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.ListInstancesResponse: + Response message containing a list of + Instances. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseListInstances._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_instances(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.ListInstances", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "ListInstances", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.ListInstancesResponse() + pb_resp = instance.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_instances(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.ListInstancesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.list_instances", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "ListInstances", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StartInstance( + _BaseInstancesRestTransport._BaseStartInstance, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.StartInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: instance.StartInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the start instance method over HTTP. + + Args: + request (~.instance.StartInstanceRequest): + The request object. Request message for starting an + Instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseStartInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_start_instance(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseStartInstance._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseInstancesRestTransport._BaseStartInstance._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseStartInstance._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.StartInstance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "StartInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._StartInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_start_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_start_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.start_instance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "StartInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StopInstance( + _BaseInstancesRestTransport._BaseStopInstance, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.StopInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: instance.StopInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the stop instance method over HTTP. + + Args: + request (~.instance.StopInstanceRequest): + The request object. Request message for deleting an + Instance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseStopInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_stop_instance(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseStopInstance._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseInstancesRestTransport._BaseStopInstance._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseStopInstance._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.StopInstance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "StopInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._StopInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_stop_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stop_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesClient.stop_instance", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "StopInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_instance( + self, + ) -> Callable[[gcr_instance.CreateInstanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance( + self, + ) -> Callable[[instance.DeleteInstanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance( + self, + ) -> Callable[[instance.GetInstanceRequest], instance.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances( + self, + ) -> Callable[[instance.ListInstancesRequest], instance.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_instance( + self, + ) -> Callable[[instance.StartInstanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_instance( + self, + ) -> Callable[[instance.StopInstanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StopInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseInstancesRestTransport._BaseDeleteOperation, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseInstancesRestTransport._BaseDeleteOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseInstancesRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseInstancesRestTransport._BaseGetOperation, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseInstancesRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.GetOperation", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseInstancesRestTransport._BaseListOperations, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseInstancesRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.ListOperations", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def wait_operation(self): + return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore + + class _WaitOperation( + _BaseInstancesRestTransport._BaseWaitOperation, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.WaitOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the wait operation method over HTTP. + + Args: + request (operations_pb2.WaitOperationRequest): + The request object for WaitOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from WaitOperation method. + """ + + http_options = ( + _BaseInstancesRestTransport._BaseWaitOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_wait_operation(request, metadata) + transcoded_request = ( + _BaseInstancesRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseInstancesRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseInstancesRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.run_v2.InstancesClient.WaitOperation", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "WaitOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_wait_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.run_v2.InstancesAsyncClient.WaitOperation", + extra={ + "serviceName": "google.cloud.run.v2.Instances", + "rpcName": "WaitOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("InstancesRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest_base.py new file mode 100644 index 000000000000..191d564512a3 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/instances/transports/rest_base.py @@ -0,0 +1,514 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance + +from .base import DEFAULT_CLIENT_INFO, InstancesTransport + + +class _BaseInstancesRestTransport(InstancesTransport): + """Base REST backend transport for Instances. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcr_instance.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseCreateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = instance.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseDeleteInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = instance.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = instance.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/instances/*}:start", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = instance.StartInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseStartInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/instances/*}:stop", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = instance.StopInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseStopInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseInstancesRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py index 2ca048759e37..853d34b258c5 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py @@ -15,6 +15,7 @@ # from .build import StorageSource, SubmitBuildRequest, SubmitBuildResponse from .condition import Condition +from .container_status import ContainerStatus from .execution import ( CancelExecutionRequest, DeleteExecutionRequest, @@ -24,6 +25,16 @@ ListExecutionsResponse, ) from .execution_template import ExecutionTemplate +from .instance import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + StartInstanceRequest, + StopInstanceRequest, +) from .instance_split import ( InstanceSplit, InstanceSplitAllocationType, @@ -123,6 +134,7 @@ "SubmitBuildRequest", "SubmitBuildResponse", "Condition", + "ContainerStatus", "CancelExecutionRequest", "DeleteExecutionRequest", "Execution", @@ -130,6 +142,14 @@ "ListExecutionsRequest", "ListExecutionsResponse", "ExecutionTemplate", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GetInstanceRequest", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "StartInstanceRequest", + "StopInstanceRequest", "InstanceSplit", "InstanceSplitStatus", "InstanceSplitAllocationType", diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/container_status.py b/packages/google-cloud-run/google/cloud/run_v2/types/container_status.py new file mode 100644 index 000000000000..ae04a3c724ca --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/types/container_status.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.run.v2", + manifest={ + "ContainerStatus", + }, +) + + +class ContainerStatus(proto.Message): + r"""ContainerStatus holds the information of container name and + image digest value. + + Attributes: + name (str): + The name of the container, if specified. + image_digest (str): + ImageDigest holds the resolved digest for the + image specified and resolved during the creation + of Revision. This field holds the digest value + regardless of whether a tag or digest was + originally specified in the Container object. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + image_digest: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/instance.py b/packages/google-cloud-run/google/cloud/run_v2/types/instance.py new file mode 100644 index 000000000000..0dfb0efdc441 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/types/instance.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.api import launch_stage_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.run_v2.types import ( + condition, + container_status, + k8s_min, + vendor_settings, +) + +__protobuf__ = proto.module( + package="google.cloud.run.v2", + manifest={ + "CreateInstanceRequest", + "GetInstanceRequest", + "DeleteInstanceRequest", + "ListInstancesRequest", + "ListInstancesResponse", + "StopInstanceRequest", + "StartInstanceRequest", + "Instance", + }, +) + + +class CreateInstanceRequest(proto.Message): + r""" + + Attributes: + parent (str): + + instance (google.cloud.run_v2.types.Instance): + + instance_id (str): + Required. The unique identifier for the Instance. It must + begin with letter, and cannot end with hyphen; must contain + fewer than 50 characters. The name of the instance becomes + {parent}/instances/{instance_id}. + validate_only (bool): + Optional. Indicates that the request should + be validated and default values populated, + without persisting the request or creating any + resources. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance: "Instance" = proto.Field( + proto.MESSAGE, + number=2, + message="Instance", + ) + instance_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetInstanceRequest(proto.Message): + r""" + + Attributes: + name (str): + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteInstanceRequest(proto.Message): + r""" + + Attributes: + name (str): + + validate_only (bool): + Optional. Indicates that the request should + be validated without actually deleting any + resources. + etag (str): + Optional. A system-generated fingerprint for + this version of the resource. May be used to + detect modification conflict during updates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListInstancesRequest(proto.Message): + r"""Request message for retrieving a list of Instances. + + Attributes: + parent (str): + Required. The location and project to list + resources on. Format: + projects/{project}/locations/{location}, where + {project} can be project id or number. + page_size (int): + Optional. Maximum number of Instances to + return in this call. + page_token (str): + Optional. A page token received from a + previous call to ListInstances. All other + parameters must match. + show_deleted (bool): + Optional. If true, returns deleted (but + unexpired) resources along with active ones. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListInstancesResponse(proto.Message): + r"""Response message containing a list of Instances. + + Attributes: + instances (MutableSequence[google.cloud.run_v2.types.Instance]): + The resulting list of Instances. + next_page_token (str): + A token indicating there are more items than page_size. Use + it in the next ListInstances request to continue. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence["Instance"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Instance", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class StopInstanceRequest(proto.Message): + r"""Request message for deleting an Instance. + + Attributes: + name (str): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + validate_only (bool): + Optional. Indicates that the request should + be validated without actually stopping any + resources. + etag (str): + Optional. A system-generated fingerprint for + this version of the resource. This may be used + to detect modification conflict during updates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StartInstanceRequest(proto.Message): + r"""Request message for starting an Instance. + + Attributes: + name (str): + Required. The name of the Instance to stop. Format: + ``projects/{project}/locations/{location}/instances/{instance}``, + where ``{project}`` can be project id or number. + validate_only (bool): + Optional. Indicates that the request should + be validated without actually stopping any + resources. + etag (str): + Optional. A system-generated fingerprint for + this version of the resource. This may be used + to detect modification conflict during updates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Instance(proto.Message): + r"""A Cloud Run Instance represents a single group of containers + running in a region. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The fully qualified name of this Instance. In + CreateInstanceRequest, this field is ignored, and instead + composed from CreateInstanceRequest.parent and + CreateInstanceRequest.instance_id. + + Format: + projects/{project}/locations/{location}/instances/{instance_id} + description (str): + User-provided description of the Instance. + This field currently has a 512-character limit. + uid (str): + Output only. Server assigned unique + identifier for the trigger. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + generation (int): + Output only. A number that monotonically increases every + time the user modifies the desired state. Please note that + unlike v1, this is an int64 value. As with most Google APIs, + its JSON representation will be a ``string`` instead of an + ``integer``. + labels (MutableMapping[str, str]): + + annotations (MutableMapping[str, str]): + + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The deletion time. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For a deleted resource, the time + after which it will be permamently deleted. + creator (str): + Output only. Email address of the + authenticated creator. + last_modifier (str): + Output only. Email address of the last + authenticated modifier. + client (str): + Arbitrary identifier for the API client. + client_version (str): + Arbitrary version identifier for the API + client. + launch_stage (google.api.launch_stage_pb2.LaunchStage): + The launch stage as defined by `Google Cloud Platform Launch + Stages `__. + Cloud Run supports ``ALPHA``, ``BETA``, and ``GA``. If no + value is specified, GA is assumed. Set the launch stage to a + preview stage on input to allow use of preview features in + that stage. On read (or output), describes whether the + resource uses preview features. + + .. raw:: html + +

+ For example, if ALPHA is provided as input, but only BETA and GA-level + features are used, this field will be BETA on output. + binary_authorization (google.cloud.run_v2.types.BinaryAuthorization): + Settings for the Binary Authorization + feature. + vpc_access (google.cloud.run_v2.types.VpcAccess): + Optional. VPC Access configuration to use for + this Revision. For more information, visit + https://cloud.google.com/run/docs/configuring/connecting-vpc. + service_account (str): + + containers (MutableSequence[google.cloud.run_v2.types.Container]): + Required. Holds the single container that + defines the unit of execution for this Instance. + volumes (MutableSequence[google.cloud.run_v2.types.Volume]): + A list of Volumes to make available to + containers. + encryption_key (str): + A reference to a customer managed encryption + key (CMEK) to use to encrypt this container + image. For more information, go to + https://cloud.google.com/run/docs/securing/using-cmek + encryption_key_revocation_action (google.cloud.run_v2.types.EncryptionKeyRevocationAction): + The action to take if the encryption key is + revoked. + encryption_key_shutdown_duration (google.protobuf.duration_pb2.Duration): + If encryption_key_revocation_action is SHUTDOWN, the + duration before shutting down all instances. The minimum + increment is 1 hour. + node_selector (google.cloud.run_v2.types.NodeSelector): + Optional. The node selector for the instance. + gpu_zonal_redundancy_disabled (bool): + Optional. True if GPU zonal redundancy is + disabled on this instance. + + This field is a member of `oneof`_ ``_gpu_zonal_redundancy_disabled``. + ingress (google.cloud.run_v2.types.IngressTraffic): + Optional. Provides the ingress settings for this Instance. + On output, returns the currently observed ingress settings, + or INGRESS_TRAFFIC_UNSPECIFIED if no revision is active. + invoker_iam_disabled (bool): + Optional. Disables IAM permission check for + run.routes.invoke for callers of this Instance. For more + information, visit + https://cloud.google.com/run/docs/securing/managing-access#invoker_check. + iap_enabled (bool): + Optional. IAP settings on the Instance. + observed_generation (int): + Output only. The generation of this Instance currently + serving traffic. See comments in ``reconciling`` for + additional information on reconciliation process in Cloud + Run. Please note that unlike v1, this is an int64 value. As + with most Google APIs, its JSON representation will be a + ``string`` instead of an ``integer``. + log_uri (str): + Output only. The Google Console URI to obtain + logs for the Instance. + terminal_condition (google.cloud.run_v2.types.Condition): + Output only. The Condition of this Instance, containing its + readiness status, and detailed error information in case it + did not reach a serving state. See comments in + ``reconciling`` for additional information on reconciliation + process in Cloud Run. + conditions (MutableSequence[google.cloud.run_v2.types.Condition]): + Output only. The Conditions of all other associated + sub-resources. They contain additional diagnostics + information in case the Instance does not reach its Serving + state. See comments in ``reconciling`` for additional + information on reconciliation process in Cloud Run. + container_statuses (MutableSequence[google.cloud.run_v2.types.ContainerStatus]): + Output only. Status information for each of + the specified containers. The status includes + the resolved digest for specified images. + satisfies_pzs (bool): + Output only. Reserved for future use. + urls (MutableSequence[str]): + Output only. All URLs serving traffic for + this Instance. + reconciling (bool): + Output only. Returns true if the Instance is currently being + acted upon by the system to bring it into the desired state. + + When a new Instance is created, or an existing one is + updated, Cloud Run will asynchronously perform all necessary + steps to bring the Instance to the desired serving state. + This process is called reconciliation. While reconciliation + is in process, ``observed_generation`` will have a transient + value that might mismatch the intended state. Once + reconciliation is over (and this field is false), there are + two possible outcomes: reconciliation succeeded and the + serving state matches the Instance, or there was an error, + and reconciliation failed. This state can be found in + ``terminal_condition.state``. + etag (str): + Optional. A system-generated fingerprint for + this version of the resource. May be used to + detect modification conflict during updates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uid: str = proto.Field( + proto.STRING, + number=4, + ) + generation: int = proto.Field( + proto.INT64, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + creator: str = proto.Field( + proto.STRING, + number=12, + ) + last_modifier: str = proto.Field( + proto.STRING, + number=13, + ) + client: str = proto.Field( + proto.STRING, + number=14, + ) + client_version: str = proto.Field( + proto.STRING, + number=15, + ) + launch_stage: launch_stage_pb2.LaunchStage = proto.Field( + proto.ENUM, + number=16, + enum=launch_stage_pb2.LaunchStage, + ) + binary_authorization: vendor_settings.BinaryAuthorization = proto.Field( + proto.MESSAGE, + number=17, + message=vendor_settings.BinaryAuthorization, + ) + vpc_access: vendor_settings.VpcAccess = proto.Field( + proto.MESSAGE, + number=18, + message=vendor_settings.VpcAccess, + ) + service_account: str = proto.Field( + proto.STRING, + number=19, + ) + containers: MutableSequence[k8s_min.Container] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=k8s_min.Container, + ) + volumes: MutableSequence[k8s_min.Volume] = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=k8s_min.Volume, + ) + encryption_key: str = proto.Field( + proto.STRING, + number=22, + ) + encryption_key_revocation_action: vendor_settings.EncryptionKeyRevocationAction = ( + proto.Field( + proto.ENUM, + number=24, + enum=vendor_settings.EncryptionKeyRevocationAction, + ) + ) + encryption_key_shutdown_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=25, + message=duration_pb2.Duration, + ) + node_selector: vendor_settings.NodeSelector = proto.Field( + proto.MESSAGE, + number=26, + message=vendor_settings.NodeSelector, + ) + gpu_zonal_redundancy_disabled: bool = proto.Field( + proto.BOOL, + number=27, + optional=True, + ) + ingress: vendor_settings.IngressTraffic = proto.Field( + proto.ENUM, + number=28, + enum=vendor_settings.IngressTraffic, + ) + invoker_iam_disabled: bool = proto.Field( + proto.BOOL, + number=29, + ) + iap_enabled: bool = proto.Field( + proto.BOOL, + number=30, + ) + observed_generation: int = proto.Field( + proto.INT64, + number=40, + ) + log_uri: str = proto.Field( + proto.STRING, + number=41, + ) + terminal_condition: condition.Condition = proto.Field( + proto.MESSAGE, + number=42, + message=condition.Condition, + ) + conditions: MutableSequence[condition.Condition] = proto.RepeatedField( + proto.MESSAGE, + number=43, + message=condition.Condition, + ) + container_statuses: MutableSequence[ + container_status.ContainerStatus + ] = proto.RepeatedField( + proto.MESSAGE, + number=44, + message=container_status.ContainerStatus, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=46, + ) + urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=45, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=98, + ) + etag: str = proto.Field( + proto.STRING, + number=99, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py b/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py index e1cd302defb3..cd640861cead 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py @@ -106,6 +106,8 @@ class Container(proto.Message): startup probe is provided, until it succeeds. Container will not be added to service endpoints if the probe fails. + readiness_probe (google.cloud.run_v2.types.Probe): + Readiness probe to be used for health checks. depends_on (MutableSequence[str]): Names of the containers that must start before this container. @@ -174,6 +176,11 @@ class Container(proto.Message): number=11, message="Probe", ) + readiness_probe: "Probe" = proto.Field( + proto.MESSAGE, + number=14, + message="Probe", + ) depends_on: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=12, diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_async.py new file mode 100644 index 000000000000..1fc8c51b7994 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_CreateInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_create_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + instance = run_v2.Instance() + instance.containers.image = "image_value" + + request = run_v2.CreateInstanceRequest( + parent="parent_value", + instance=instance, + instance_id="instance_id_value", + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_CreateInstance_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_sync.py new file mode 100644 index 000000000000..39d9fa1b256a --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_create_instance_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_CreateInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_create_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + instance = run_v2.Instance() + instance.containers.image = "image_value" + + request = run_v2.CreateInstanceRequest( + parent="parent_value", + instance=instance, + instance_id="instance_id_value", + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_CreateInstance_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_async.py new file mode 100644 index 000000000000..c76fcf12f232 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_DeleteInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_delete_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_DeleteInstance_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_sync.py new file mode 100644 index 000000000000..7d91afa34a61 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_delete_instance_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_DeleteInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_delete_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_DeleteInstance_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_async.py new file mode 100644 index 000000000000..4353b113fe60 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_GetInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_get_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_GetInstance_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_sync.py new file mode 100644 index 000000000000..a07bce426cf7 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_get_instance_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_GetInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_get_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_GetInstance_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_async.py new file mode 100644 index 000000000000..5f07e59dd63f --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_ListInstances_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_list_instances(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END run_v2_generated_Instances_ListInstances_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_sync.py new file mode 100644 index 000000000000..dc9e58b88e36 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_list_instances_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListInstances +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_ListInstances_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_list_instances(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END run_v2_generated_Instances_ListInstances_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_async.py new file mode 100644 index 000000000000..51ae8e362d19 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_StartInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_start_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.StartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.start_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_StartInstance_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_sync.py new file mode 100644 index 000000000000..e59bfa3336f4 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_start_instance_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_StartInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_start_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.StartInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.start_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_StartInstance_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_async.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_async.py new file mode 100644 index 000000000000..bc013687d006 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_StopInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +async def sample_stop_instance(): + # Create a client + client = run_v2.InstancesAsyncClient() + + # Initialize request argument(s) + request = run_v2.StopInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_StopInstance_async] diff --git a/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_sync.py b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_sync.py new file mode 100644 index 000000000000..1f4e5bd9af65 --- /dev/null +++ b/packages/google-cloud-run/samples/generated_samples/run_v2_generated_instances_stop_instance_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopInstance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-run + + +# [START run_v2_generated_Instances_StopInstance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import run_v2 + + +def sample_stop_instance(): + # Create a client + client = run_v2.InstancesClient() + + # Initialize request argument(s) + request = run_v2.StopInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END run_v2_generated_Instances_StopInstance_sync] diff --git a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json index 8b7a4f6c85eb..8a7691c710ae 100644 --- a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json +++ b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json @@ -808,6 +808,980 @@ ], "title": "run_v2_generated_executions_list_executions_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.CreateInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.run_v2.types.Instance" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "run_v2_generated_instances_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_CreateInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.create_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.CreateInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.run_v2.types.Instance" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "run_v2_generated_instances_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_CreateInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.DeleteInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "run_v2_generated_instances_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_DeleteInstance_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.delete_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.DeleteInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "run_v2_generated_instances_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_DeleteInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.GetInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.run_v2.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "run_v2_generated_instances_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_GetInstance_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.get_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.GetInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.run_v2.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "run_v2_generated_instances_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_GetInstance_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.run.v2.Instances.ListInstances", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.run_v2.services.instances.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "run_v2_generated_instances_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_ListInstances_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.list_instances", + "method": { + "fullName": "google.cloud.run.v2.Instances.ListInstances", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.run_v2.services.instances.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "run_v2_generated_instances_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_ListInstances_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.start_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.StartInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "StartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.StartInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "start_instance" + }, + "description": "Sample for StartInstance", + "file": "run_v2_generated_instances_start_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_StartInstance_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_start_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.start_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.StartInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "StartInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.StartInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "start_instance" + }, + "description": "Sample for StartInstance", + "file": "run_v2_generated_instances_start_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_StartInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_start_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.InstancesAsyncClient", + "shortName": "InstancesAsyncClient" + }, + "fullName": "google.cloud.run_v2.InstancesAsyncClient.stop_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.StopInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "StopInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.StopInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "stop_instance" + }, + "description": "Sample for StopInstance", + "file": "run_v2_generated_instances_stop_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_StopInstance_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_stop_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.run_v2.InstancesClient.stop_instance", + "method": { + "fullName": "google.cloud.run.v2.Instances.StopInstance", + "service": { + "fullName": "google.cloud.run.v2.Instances", + "shortName": "Instances" + }, + "shortName": "StopInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.StopInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "stop_instance" + }, + "description": "Sample for StopInstance", + "file": "run_v2_generated_instances_stop_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Instances_StopInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_instances_stop_instance_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_instances.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_instances.py new file mode 100644 index 000000000000..b89483ae7d5c --- /dev/null +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_instances.py @@ -0,0 +1,8059 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api import launch_stage_pb2 # type: ignore +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.run_v2.services.instances import ( + InstancesAsyncClient, + InstancesClient, + pagers, + transports, +) +from google.cloud.run_v2.types import condition, container_status +from google.cloud.run_v2.types import instance +from google.cloud.run_v2.types import instance as gcr_instance +from google.cloud.run_v2.types import k8s_min, vendor_settings + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# 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 + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +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 InstancesClient._get_default_mtls_endpoint(None) is None + assert InstancesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + InstancesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + InstancesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + InstancesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert InstancesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert InstancesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert InstancesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert InstancesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + InstancesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert InstancesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert InstancesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert InstancesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert InstancesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + InstancesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert InstancesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert InstancesClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert InstancesClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert InstancesClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert InstancesClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + InstancesClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert InstancesClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert InstancesClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert InstancesClient._get_client_cert_source(None, False) is None + assert ( + InstancesClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + InstancesClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + InstancesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + InstancesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + InstancesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesClient), +) +@mock.patch.object( + InstancesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = InstancesClient._DEFAULT_UNIVERSE + default_endpoint = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + InstancesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + InstancesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == InstancesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstancesClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + InstancesClient._get_api_endpoint(None, None, default_universe, "always") + == InstancesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstancesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == InstancesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstancesClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + InstancesClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + InstancesClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + InstancesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + InstancesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + InstancesClient._get_universe_domain(None, None) + == InstancesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + InstancesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = InstancesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = InstancesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (InstancesClient, "grpc"), + (InstancesAsyncClient, "grpc_asyncio"), + (InstancesClient, "rest"), + ], +) +def test_instances_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.InstancesGrpcTransport, "grpc"), + (transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.InstancesRestTransport, "rest"), + ], +) +def test_instances_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (InstancesClient, "grpc"), + (InstancesAsyncClient, "grpc_asyncio"), + (InstancesClient, "rest"), + ], +) +def test_instances_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) + + +def test_instances_client_get_transport_class(): + transport = InstancesClient.get_transport_class() + available_transports = [ + transports.InstancesGrpcTransport, + transports.InstancesRestTransport, + ] + assert transport in available_transports + + transport = InstancesClient.get_transport_class("grpc") + assert transport == transports.InstancesGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc"), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (InstancesClient, transports.InstancesRestTransport, "rest"), + ], +) +@mock.patch.object( + InstancesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesClient), +) +@mock.patch.object( + InstancesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesAsyncClient), +) +def test_instances_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(InstancesClient, "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(InstancesClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc", "true"), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (InstancesClient, transports.InstancesGrpcTransport, "grpc", "false"), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (InstancesClient, transports.InstancesRestTransport, "rest", "true"), + (InstancesClient, transports.InstancesRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + InstancesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesClient), +) +@mock.patch.object( + InstancesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_instances_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient]) +@mock.patch.object( + InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient) +) +@mock.patch.object( + InstancesAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(InstancesAsyncClient), +) +def test_instances_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient]) +@mock.patch.object( + InstancesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesClient), +) +@mock.patch.object( + InstancesAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstancesAsyncClient), +) +def test_instances_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = InstancesClient._DEFAULT_UNIVERSE + default_endpoint = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = InstancesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc"), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (InstancesClient, transports.InstancesRestTransport, "rest"), + ], +) +def test_instances_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc", grpc_helpers), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (InstancesClient, transports.InstancesRestTransport, "rest", None), + ], +) +def test_instances_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_instances_client_client_options_from_dict(): + with mock.patch( + "google.cloud.run_v2.services.instances.transports.InstancesGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = InstancesClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc", grpc_helpers), + ( + InstancesAsyncClient, + transports.InstancesGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_instances_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "run.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcr_instance.CreateInstanceRequest, + dict, + ], +) +def test_create_instance(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcr_instance.CreateInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcr_instance.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcr_instance.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + ) + + +def test_create_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_instance + ] = mock_rpc + + request = {} + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_instance_async( + transport: str = "grpc_asyncio", request_type=gcr_instance.CreateInstanceRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcr_instance.CreateInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__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_instance( + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].instance + mock_val = gcr_instance.Instance(name="name_value") + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = InstancesClient( + credentials=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_instance( + gcr_instance.CreateInstanceRequest(), + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__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_instance( + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].instance + mock_val = gcr_instance.Instance(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_instance( + gcr_instance.CreateInstanceRequest(), + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = instance.DeleteInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = instance.DeleteInstanceRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance.DeleteInstanceRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + request = {} + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_instance + ] = mock_rpc + + request = {} + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_instance_async( + transport: str = "grpc_asyncio", request_type=instance.DeleteInstanceRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = instance.DeleteInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_instance_flattened_error(): + client = InstancesClient( + credentials=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_instance( + instance.DeleteInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_instance_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_instance( + instance.DeleteInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.GetInstanceRequest, + dict, + ], +) +def test_get_instance(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.Instance( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service_account="service_account_value", + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + gpu_zonal_redundancy_disabled=True, + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + invoker_iam_disabled=True, + iap_enabled=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + urls=["urls_value"], + reconciling=True, + etag="etag_value", + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = instance.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service_account == "service_account_value" + assert response.encryption_key == "encryption_key_value" + assert ( + response.encryption_key_revocation_action + == vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW + ) + assert response.gpu_zonal_redundancy_disabled is True + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.invoker_iam_disabled is True + assert response.iap_enabled is True + assert response.observed_generation == 2021 + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.urls == ["urls_value"] + assert response.reconciling is True + assert response.etag == "etag_value" + + +def test_get_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = instance.GetInstanceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance.GetInstanceRequest( + name="name_value", + ) + + +def test_get_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_instance + ] = mock_rpc + + request = {} + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_instance_async( + transport: str = "grpc_asyncio", request_type=instance.GetInstanceRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service_account="service_account_value", + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + gpu_zonal_redundancy_disabled=True, + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + invoker_iam_disabled=True, + iap_enabled=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + urls=["urls_value"], + reconciling=True, + etag="etag_value", + ) + ) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = instance.GetInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service_account == "service_account_value" + assert response.encryption_key == "encryption_key_value" + assert ( + response.encryption_key_revocation_action + == vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW + ) + assert response.gpu_zonal_redundancy_disabled is True + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.invoker_iam_disabled is True + assert response.iap_enabled is True + assert response.observed_generation == 2021 + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.urls == ["urls_value"] + assert response.reconciling is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_instance_flattened_error(): + client = InstancesClient( + credentials=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_instance( + instance.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_instance_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_instance( + instance.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.ListInstancesRequest, + dict, + ], +) +def test_list_instances(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.ListInstancesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = instance.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = instance.ListInstancesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance.ListInstancesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_instances_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_instances + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_instances + ] = mock_rpc + + request = {} + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_instances_async( + transport: str = "grpc_asyncio", request_type=instance.ListInstancesRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.ListInstancesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = instance.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_instances_flattened_error(): + client = InstancesClient( + credentials=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_instances( + instance.ListInstancesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = instance.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.ListInstancesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_instances_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_instances( + instance.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_instances(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.Instance) for i in results) + + +def test_list_instances_pages(transport_name: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.Instance) for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_instances(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StopInstanceRequest, + dict, + ], +) +def test_stop_instance(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = instance.StopInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_stop_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = instance.StopInstanceRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.stop_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance.StopInstanceRequest( + name="name_value", + etag="etag_value", + ) + + +def test_stop_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.stop_instance] = mock_rpc + request = {} + client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.stop_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_stop_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.stop_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.stop_instance + ] = mock_rpc + + request = {} + await client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.stop_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_stop_instance_async( + transport: str = "grpc_asyncio", request_type=instance.StopInstanceRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__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.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = instance.StopInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_stop_instance_async_from_dict(): + await test_stop_instance_async(request_type=dict) + + +def test_stop_instance_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = instance.StopInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_instance_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = instance.StopInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_instance_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__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.stop_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_stop_instance_flattened_error(): + client = InstancesClient( + credentials=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_instance( + instance.StopInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_stop_instance_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__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.stop_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_stop_instance_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_instance( + instance.StopInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StartInstanceRequest, + dict, + ], +) +def test_start_instance(request_type, transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = instance.StartInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = instance.StartInstanceRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.start_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == instance.StartInstanceRequest( + name="name_value", + etag="etag_value", + ) + + +def test_start_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.start_instance] = mock_rpc + request = {} + client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_start_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.start_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.start_instance + ] = mock_rpc + + request = {} + await client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.start_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_start_instance_async( + transport: str = "grpc_asyncio", request_type=instance.StartInstanceRequest +): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_instance), "__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.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = instance.StartInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_start_instance_async_from_dict(): + await test_start_instance_async(request_type=dict) + + +def test_start_instance_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = instance.StartInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_instance_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = instance.StartInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_instance_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__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.start_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_start_instance_flattened_error(): + client = InstancesClient( + credentials=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_instance( + instance.StartInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_start_instance_flattened_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__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.start_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_start_instance_flattened_error_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_instance( + instance.StartInstanceRequest(), + name="name_value", + ) + + +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=gcr_instance.CreateInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "instance_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instance", + "instanceId", + ) + ) + ) + + +def test_create_instance_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/instances" % client.transport._host, + args[1], + ) + + +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_instance( + gcr_instance.CreateInstanceRequest(), + parent="parent_value", + instance=gcr_instance.Instance(name="name_value"), + ) + + +def test_delete_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + + request = {} + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_instance_rest_required_fields( + request_type=instance.DeleteInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_instance_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_instance( + instance.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_get_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_instance_rest_required_fields(request_type=instance.GetInstanceRequest): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_instance_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + instance.GetInstanceRequest(), + name="name_value", + ) + + +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_instances_rest_required_fields( + request_type=instance.ListInstancesRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_instances_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*/locations/*}/instances" % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + instance.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(instance.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_stop_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.stop_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.stop_instance] = mock_rpc + + request = {} + client.stop_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.stop_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_stop_instance_rest_required_fields(request_type=instance.StopInstanceRequest): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).stop_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).stop_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.stop_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_stop_instance_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.stop_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_stop_instance_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.stop_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/instances/*}:stop" + % client.transport._host, + args[1], + ) + + +def test_stop_instance_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_instance( + instance.StopInstanceRequest(), + name="name_value", + ) + + +def test_start_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.start_instance] = mock_rpc + + request = {} + client.start_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_start_instance_rest_required_fields( + request_type=instance.StartInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).start_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).start_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.start_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_start_instance_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_start_instance_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.start_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/locations/*/instances/*}:start" + % client.transport._host, + args[1], + ) + + +def test_start_instance_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_instance( + instance.StartInstanceRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = InstancesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = InstancesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = InstancesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.InstancesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, + transports.InstancesRestTransport, + ], +) +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_kind_grpc(): + transport = InstancesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = instance.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = instance.ListInstancesResponse() + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_instance_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.stop_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StopInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_instance_empty_call_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StartInstanceRequest() + + assert args[0] == request_msg + + +def test_create_instance_routing_parameters_request_1_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_instance_routing_parameters_request_1_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_instance_routing_parameters_request_1_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = instance.Instance() + client.get_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.GetInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_instances_routing_parameters_request_1_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = instance.ListInstancesResponse() + client.list_instances(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.ListInstancesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_grpc_asyncio(): + transport = InstancesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service_account="service_account_value", + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + gpu_zonal_redundancy_disabled=True, + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + invoker_iam_disabled=True, + iap_enabled=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + urls=["urls_value"], + reconciling=True, + etag="etag_value", + ) + ) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.ListInstancesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_stop_instance_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.stop_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StopInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_start_instance_empty_call_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.start_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StartInstanceRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_instance_routing_parameters_request_1_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance( + request={"parent": "projects/sample1/locations/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_instance_routing_parameters_request_1_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_instance_routing_parameters_request_1_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service_account="service_account_value", + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + gpu_zonal_redundancy_disabled=True, + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + invoker_iam_disabled=True, + iap_enabled=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + urls=["urls_value"], + reconciling=True, + etag="etag_value", + ) + ) + await client.get_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.GetInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_instances_routing_parameters_request_1_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.ListInstancesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_instances( + request={"parent": "projects/sample1/locations/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.ListInstancesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_rest(): + transport = InstancesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_instance_rest_bad_request( + request_type=gcr_instance.CreateInstanceRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcr_instance.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "policy": "policy_value", + "breakglass_justification": "breakglass_justification_value", + }, + "vpc_access": { + "connector": "connector_value", + "egress": 1, + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "tags": ["tags_value1", "tags_value2"], + } + ], + }, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "source_code": { + "cloud_storage_source": { + "bucket": "bucket_value", + "object_": "object__value", + "generation": 1068, + } + }, + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": { + "limits": {}, + "cpu_idle": True, + "startup_cpu_boost": True, + }, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + { + "name": "name_value", + "mount_path": "mount_path_value", + "sub_path": "sub_path_value", + } + ], + "working_dir": "working_dir_value", + "liveness_probe": { + "initial_delay_seconds": 2214, + "timeout_seconds": 1621, + "period_seconds": 1489, + "failure_threshold": 1812, + "http_get": { + "path": "path_value", + "http_headers": [ + {"name": "name_value", "value": "value_value"} + ], + "port": 453, + }, + "tcp_socket": {"port": 453}, + "grpc": {"port": 453, "service": "service_value"}, + }, + "startup_probe": {}, + "readiness_probe": {}, + "depends_on": ["depends_on_value1", "depends_on_value2"], + "base_image_uri": "base_image_uri_value", + "build_info": { + "function_target": "function_target_value", + "source_location": "source_location_value", + }, + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + {"path": "path_value", "version": "version_value", "mode": 421} + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": { + "bucket": "bucket_value", + "read_only": True, + "mount_options": ["mount_options_value1", "mount_options_value2"], + }, + } + ], + "encryption_key": "encryption_key_value", + "encryption_key_revocation_action": 1, + "encryption_key_shutdown_duration": {"seconds": 751, "nanos": 543}, + "node_selector": {"accelerator": "accelerator_value"}, + "gpu_zonal_redundancy_disabled": True, + "ingress": 1, + "invoker_iam_disabled": True, + "iap_enabled": True, + "observed_generation": 2021, + "log_uri": "log_uri_value", + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "container_statuses": [ + {"name": "name_value", "image_digest": "image_digest_value"} + ], + "satisfies_pzs": True, + "urls": ["urls_value1", "urls_value2"], + "reconciling": True, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcr_instance.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.InstancesRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_create_instance_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcr_instance.CreateInstanceRequest.pb( + gcr_instance.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcr_instance.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_instance_rest_bad_request(request_type=instance.DeleteInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.InstancesRestInterceptor, "post_delete_instance" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_delete_instance_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.DeleteInstanceRequest.pb(instance.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = instance.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=instance.GetInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service_account="service_account_value", + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + gpu_zonal_redundancy_disabled=True, + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + invoker_iam_disabled=True, + iap_enabled=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + urls=["urls_value"], + reconciling=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service_account == "service_account_value" + assert response.encryption_key == "encryption_key_value" + assert ( + response.encryption_key_revocation_action + == vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW + ) + assert response.gpu_zonal_redundancy_disabled is True + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.invoker_iam_disabled is True + assert response.iap_enabled is True + assert response.observed_generation == 2021 + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.urls == ["urls_value"] + assert response.reconciling is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.InstancesRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_get_instance_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.GetInstanceRequest.pb(instance.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.content = return_value + + request = instance.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + post_with_metadata.return_value = instance.Instance(), metadata + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_instances_rest_bad_request(request_type=instance.ListInstancesRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.InstancesRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_list_instances_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.ListInstancesRequest.pb(instance.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.ListInstancesResponse.to_json( + instance.ListInstancesResponse() + ) + req.return_value.content = return_value + + request = instance.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.ListInstancesResponse() + post_with_metadata.return_value = instance.ListInstancesResponse(), metadata + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_stop_instance_rest_bad_request(request_type=instance.StopInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.stop_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StopInstanceRequest, + dict, + ], +) +def test_stop_instance_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.stop_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_instance_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.InstancesRestInterceptor, "post_stop_instance" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_stop_instance_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_stop_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.StopInstanceRequest.pb(instance.StopInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = instance.StopInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.stop_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_start_instance_rest_bad_request(request_type=instance.StartInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.start_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StartInstanceRequest, + dict, + ], +) +def test_start_instance_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.start_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_instance_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.InstancesRestInterceptor, "post_start_instance" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_start_instance_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_start_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.StartInstanceRequest.pb(instance.StartInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = instance.StartInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.start_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_stop_instance_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.stop_instance), "__call__") as call: + client.stop_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StopInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_start_instance_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_instance), "__call__") as call: + client.start_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.StartInstanceRequest() + + assert args[0] == request_msg + + +def test_create_instance_routing_parameters_request_1_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_instance.CreateInstanceRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_instance_routing_parameters_request_1_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_instance_routing_parameters_request_1_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.GetInstanceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_instances_routing_parameters_request_1_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = instance.ListInstancesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_instances_rest_lro_client(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.InstancesGrpcTransport, + ) + + +def test_instances_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.InstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_instances_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.run_v2.services.instances.transports.InstancesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.InstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_instance", + "delete_instance", + "get_instance", + "list_instances", + "stop_instance", + "start_instance", + "get_operation", + "wait_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_instances_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.run_v2.services.instances.transports.InstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport( + 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",), + quota_project_id="octopus", + ) + + +def test_instances_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.run_v2.services.instances.transports.InstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport() + adc.assert_called_once() + + +def test_instances_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) + InstancesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, + ], +) +def test_instances_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",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, + transports.InstancesRestTransport, + ], +) +def test_instances_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstancesGrpcTransport, grpc_helpers), + (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_instances_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( + "run.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="run.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport], +) +def test_instances_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_instances_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.InstancesRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_instances_host_no_port(transport_name): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="run.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_instances_host_with_port(transport_name): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="run.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "run.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_instances_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = InstancesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = InstancesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.stop_instance._session + session2 = client2.transport.stop_instance._session + assert session1 != session2 + session1 = client1.transport.start_instance._session + session2 = client2.transport.start_instance._session + assert session1 != session2 + + +def test_instances_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.InstancesGrpcTransport( + 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_instances_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.InstancesGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport], +) +def test_instances_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport], +) +def test_instances_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_instances_grpc_lro_client(): + client = InstancesClient( + 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_instances_grpc_lro_async_client(): + client = InstancesAsyncClient( + 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_connector_path(): + project = "squid" + location = "clam" + connector = "whelk" + expected = "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) + actual = InstancesClient.connector_path(project, location, connector) + assert expected == actual + + +def test_parse_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "connector": "nudibranch", + } + path = InstancesClient.connector_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_connector_path(path) + assert expected == actual + + +def test_crypto_key_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + crypto_key = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = InstancesClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "crypto_key": "clam", + } + path = InstancesClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_instance_path(): + project = "whelk" + location = "octopus" + instance = "oyster" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = InstancesClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "instance": "mussel", + } + path = InstancesClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_instance_path(path) + assert expected == actual + + +def test_policy_path(): + project = "winkle" + expected = "projects/{project}/policy".format( + project=project, + ) + actual = InstancesClient.policy_path(project) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "project": "nautilus", + } + path = InstancesClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_policy_path(path) + assert expected == actual + + +def test_secret_path(): + project = "scallop" + secret = "abalone" + expected = "projects/{project}/secrets/{secret}".format( + project=project, + secret=secret, + ) + actual = InstancesClient.secret_path(project, secret) + assert expected == actual + + +def test_parse_secret_path(): + expected = { + "project": "squid", + "secret": "clam", + } + path = InstancesClient.secret_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_secret_path(path) + assert expected == actual + + +def test_secret_version_path(): + project = "whelk" + secret = "octopus" + version = "oyster" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + actual = InstancesClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "nudibranch", + "secret": "cuttlefish", + "version": "mussel", + } + path = InstancesClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_secret_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 = InstancesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = InstancesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = InstancesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = InstancesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = InstancesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = InstancesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = InstancesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = InstancesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.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 = InstancesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = InstancesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.InstancesTransport, "_prep_wrapped_messages" + ) as prep: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.InstancesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = InstancesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_wait_operation(transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.WaitOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.wait_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_wait_operation(transport: str = "grpc_asyncio"): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.WaitOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.wait_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_wait_operation_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.WaitOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.wait_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_wait_operation_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.WaitOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.wait_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_wait_operation_from_dict(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.wait_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_wait_operation_from_dict_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.wait_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = InstancesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (InstancesClient, transports.InstancesGrpcTransport), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py index aadf03d61d69..d2cc524d71b3 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py @@ -6502,6 +6502,7 @@ def test_create_job_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": { @@ -7121,6 +7122,7 @@ def test_update_job_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": { diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py index 7cc2d3230665..858272e6bbc1 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py @@ -6100,6 +6100,7 @@ def test_create_service_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": { @@ -6790,6 +6791,7 @@ def test_update_service_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": { diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_worker_pools.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_worker_pools.py index e5fa3c08b373..f52ace051bba 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_worker_pools.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_worker_pools.py @@ -6221,6 +6221,7 @@ def test_create_worker_pool_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": { @@ -6875,6 +6876,7 @@ def test_update_worker_pool_rest_call_success(request_type): "grpc": {"port": 453, "service": "service_value"}, }, "startup_probe": {}, + "readiness_probe": {}, "depends_on": ["depends_on_value1", "depends_on_value2"], "base_image_uri": "base_image_uri_value", "build_info": {